现在(6 年后)容易多了!
Spawn 返回一个childObject,然后您可以使用它来监听事件。这些事件是:
- 类:子进程
- 事件:'错误'
- 事件:“退出”
- 事件:'关闭'
- 事件:“断开连接”
- 事件:'消息'
还有一堆来自 childObject 的对象,它们是:
- 类:子进程
- 子标准输入
- child.stdout
- child.stderr
- 孩子.stdio
- 孩子.pid
- 子连接
- child.kill([信号])
- child.send(message[, sendHandle][, callback])
- child.disconnect()
在此处查看有关 childObject 的更多信息:https ://nodejs.org/api/child_process.html
异步
如果您想在节点仍然能够继续执行的情况下在后台运行您的进程,请使用异步方法。您仍然可以选择在流程完成后以及流程有任何输出时执行操作(例如,如果您想将脚本的输出发送到客户端)。
child_process.spawn(...); (节点 v0.1.90)
var spawn = require('child_process').spawn;
var child = spawn('node ./commands/server.js');
// You can also use a variable to save the output
// for when the script closes later
var scriptOutput = "";
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) {
//Here is where the output goes
console.log('stdout: ' + data);
data=data.toString();
scriptOutput+=data;
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', function(data) {
//Here is where the error output goes
console.log('stderr: ' + data);
data=data.toString();
scriptOutput+=data;
});
child.on('close', function(code) {
//Here you can get the exit code of the script
console.log('closing code: ' + code);
console.log('Full output of script: ',scriptOutput);
});
以下是使用回调 + 异步方法的方法:
var child_process = require('child_process');
console.log("Node Version: ", process.version);
run_script("ls", ["-l", "/home"], function(output, exit_code) {
console.log("Process Finished.");
console.log('closing code: ' + exit_code);
console.log('Full output of script: ',output);
});
console.log ("Continuing to do node things while the process runs at the same time...");
// This function will output the lines from the script
// AS is runs, AND will return the full combined output
// as well as exit code when it's done (using the callback).
function run_script(command, args, callback) {
console.log("Starting Process.");
var child = child_process.spawn(command, args);
var scriptOutput = "";
child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) {
console.log('stdout: ' + data);
data=data.toString();
scriptOutput+=data;
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', function(data) {
console.log('stderr: ' + data);
data=data.toString();
scriptOutput+=data;
});
child.on('close', function(code) {
callback(scriptOutput,code);
});
}
使用上述方法,您可以将脚本的每一行输出发送到客户端(例如,当您在stdout
or上接收事件时使用 Socket.io 发送每一行stderr
)。
同步
如果您希望节点停止它正在做的事情并等待脚本完成,您可以使用同步版本:
child_process.spawnSync(...); (节点 v0.11.12+)
这种方法的问题:
- 如果脚本需要一段时间才能完成,您的服务器将在这段时间内挂起!
- 只有脚本完成运行后才会返回标准输出。因为它是同步的,所以在当前行完成之前无法继续。因此,在生成线完成之前,它无法捕获“stdout”事件。
如何使用它:
var child_process = require('child_process');
var child = child_process.spawnSync("ls", ["-l", "/home"], { encoding : 'utf8' });
console.log("Process finished.");
if(child.error) {
console.log("ERROR: ",child.error);
}
console.log("stdout: ",child.stdout);
console.log("stderr: ",child.stderr);
console.log("exist code: ",child.status);