无法执行child_process.exec(“node child.js”)

时间:2013-03-22 08:07:34

标签: node.js

我在一个名为“app.js”和“child.js”的文件夹下有两个文件。节点正在Windows操作系统上运行。 app.js文件:

;(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");
})();  

child.js文件:

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

我试图通过“exec”方法执行外部命令 但是当我跑步时:

node app.js  

我收到错误:

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

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

因此,如果您想要exec命令,请尝试以下操作:

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

process.execPath包含node.exe的完整路径,"应该在那里,因为目录名称可以包含Program files之类的空格。

子进程是相同的,我刚刚将process.env.envVar更改为process.env.number,因为您在exec选项中进行了设置。

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