无法执行child_process.exec(“node child.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.
我在这里做什么错了?
所以如果你想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的完整path, "
应该在那里,因为目录名称可以包含像Program files
这样的空格。
subprocess是一样的,我只是把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));