【问题标题】:Unable to execute child_process.exec("node child.js")无法执行 child_process.exec("node child.js")
【发布时间】:2013-03-22 08:07:34
【问题描述】:

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

我在这里做错了什么?

【问题讨论】:

  • 听起来你没有安装node
  • @Alex:我已经安装了节点。当我在命令行上写“节点”时,我得到了 REPL。
  • 您应该使用 fork 而不是 exec 来启动节点进程。 nodejs.org/api/…
  • @generalhenry:如果我写 exec("dir *.*", function(err, stdout, stderr) {}),它工作正常。我无法理解为什么在上述情况下它会失败。
  • 可能节点不在PATH 中,尝试exec("path", function(err, stdout, stderr) {}),然后将路径中的内容打印到控制台。您也可以指定节点的整个路径,例如c:\Program Files\nodejs\node.exe child.js

标签: node.js


【解决方案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));

【讨论】:

    猜你喜欢
    • 2013-04-30
    • 2017-04-22
    • 2012-12-11
    • 2019-03-02
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2018-03-14
    相关资源
    最近更新 更多