Anup Vasudeva
Anup Vasudeva

Reputation: 901

Unable to execute child_process.exec("node child.js")

I have two files under a folder with names "app.js" and "child.js". The Node is running on Windows OS. The app.js file:

;(function() {
    var http = require("http"),
    child_process = require("child_process"),
    exec = child_process.exec;

    http.createServer(function(request, response) {
        response.writeHead(200, {"content-type": "text/plain"});
        exec('node child.js', {env: {number: 1234}}, function(error, stdout, stderror) {
            if(error) throw error;
            console.log(stdout);
            console.log(stderror);
        });
        response.write("Hello world!!!");
        response.end();
    }).listen(8000);
    console.log("The server has started listening to the port: 8000");
})();  

The child.js file:

;(function() {
    var envVar = process.env.envVar;
    console.log("Type of envVar: " + typeof envVar);
    console.log("The value of envVar is: " + parseInt(envVar, 10));
})();

I am attempting to execute an external command via "exec" method.
But when I run:

node app.js  

I receive the error:

Command failed: 'node' is not recognized as an internal or external command, operable program or batch file.  

What wrong am I doing here?

Upvotes: 1

Views: 6429

Answers (1)

balazs
balazs

Reputation: 5788

So if you want to exec a command, try this:

var http = require("http"),
    child_process = require("child_process"),
    exec = child_process.exec;
    http.createServer(function(request, response) {
        response.writeHead(200, {"content-type": "text/plain"});
        exec( '"' + process.execPath + '" child.js', {env: {number: 1234}}, function(error, stdout, stderror) {
            if(error) throw error;
            console.log(stdout);
            console.log(stderror);
        });
        response.write("Hello world!!!");
        response.end();
    }).listen(8000);
    console.log("The server has started listening to the port: 8000");

the process.execPath contains the full path of node.exe, the " should be there, because directory names can contain spaces like Program files.

the child process is the same, I just changed process.env.envVar to process.env.number, because you set that in exec options.

var envVar = process.env.number;
    console.log("Type of envVar: " + typeof envVar);
    console.log("The value of envVar is: " + parseInt(envVar, 10));

Upvotes: 1

Related Questions