简体   繁体   中英

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?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM