1

我在一个名为“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.  

我在这里做错了什么?

4

1 回答 1

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.envVarprocess.env.number因为你在execoptions中设置了。

var envVar = process.env.number;
    console.log("Type of envVar: " + typeof envVar);
    console.log("The value of envVar is: " + parseInt(envVar, 10));
于 2013-03-22T10:05:11.343 回答