如何从另一个Node.js脚本中运行Node.js脚本

我有一个独立的Node脚本,名为compile.js 。 它坐在一个小型快递应用程序的主文件夹内。

有时我会从命令行运行compile.js脚本。 在其他情况下,我希望它由Express应用程序执行。

这两个脚本都从package.json加载configuration数据。 Compile.js目前不能导出任何方法。

加载这个文件并执行它的最好方法是什么? 我已经看了eval()vm.RunInNewContext ,并require ,但不知道什么是正确的方法。

谢谢你的帮助!!

您可以使用subprocess来运行该脚本,并监听退出和错误事件以了解何时完成该进程或出错(在某些情况下可能导致退出事件不会触发)。 这种方法的优点是可以处理任何asynchronous脚本,即使那些没有明确devise为可以作为subprocess运行的asynchronous脚本,比如你想要调用的第三方脚本。 例:

 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, eg runScript('./some-script.js', function (err) { if (err) throw err; console.log('finished running some-script.js'); }); 

请注意,如果在可能存在安全问题的环境中运行第三方脚本,最好在沙盒虚拟机上下文中运行该脚本。

分叉subprocess可能是有用的,请参阅http://nodejs.org/api/child_process.html

从链接的例子:

 var cp = require('child_process'); var n = cp.fork(__dirname + '/sub.js'); n.on('message', function(m) { console.log('PARENT got message:', m); }); n.send({ hello: 'world' }); 

现在,subprocess将会像…也是这样的例子:

 process.on('message', function(m) { console.log('CHILD got message:', m); }); process.send({ foo: 'bar' }); 

但要做简单的任务,我认为创build一个模块,扩展events.EventEmitter类将做… http://nodejs.org/api/events.html