您可以使用子进程来运行脚本,并监听退出和错误事件以了解进程何时完成或出错(在某些情况下可能会导致退出事件未触发)。这种方法的优点是可以处理任何异步脚本,即使那些没有明确设计为可以作为子进程运行的异步脚本,比如您想要调用的第三方脚本。例如:
var childProcess = require('child_process');
function runScript(scriptPath, callback) {
// keep track of whether callback has been invoked to prevent multiple invocations
var invoked = false;
var process = childProcess.fork(scriptPath);
// listen for errors as they may prevent the exit event from firing
process.on('error', function (err) {
if (invoked) return;
invoked = true;
callback(err);
});
// execute the callback once the process has finished running
process.on('exit', function (code) {
if (invoked) return;
invoked = true;
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
}
// Now we can run a script and invoke a callback when complete, e.g.
runScript('./some-script.js', function (err) {
if (err) throw err;
console.log('finished running some-script.js');
});
注意,如果在安全问题可能存在的环境中运行第三方脚本,它可能是最好的沙盒VM上下文运行该脚本。
你是否考虑过var exec = require('child_process')。exec; exec('节点 /compile.js',...)? –
huocp
请问http://nodejs.org/api/process.html#process_process_execargv是否符合您的需求? –
为什么不简单地要求()呢? – dandavis