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

我有一个独立的节点脚本称为 compile.js。它是坐在一个小快递应用程序的主文件夹内。

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

这两个脚本都从 package.json.Compile.js加载配置数据。此时 Compile.js不导出任何方法。

加载并执行这个文件的最佳方法是什么?我研究了 eval()vm.RunInNewContextrequire,但不确定什么是正确的方法。

谢谢你的帮助! !

80165 次浏览

Forking a child process may be useful, see http://nodejs.org/api/child_process.html

From the example at link:

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' });

Now, the child process would go like... also from the example:

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


process.send({ foo: 'bar' });

But to do simple tasks I think that creating a module that extends the events.EventEmitter class will do... http://nodejs.org/api/events.html

You can use a child process to run the script, and listen for exit and error events to know when the process is completed or errors out (which in some cases may result in the exit event not firing). This method has the advantage of working with any async script, even those that are not explicitly designed to be run as a child process, such as a third party script you would like to invoke. Example:

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');
});

Note that if running third-party scripts in an environment where security issues may exist, it may be preferable to run the script in a sandboxed vm context.

Put this line in anywhere of the Node application.

require('child_process').fork('some_code.js'); //change the path depending on where the file is.

In some_code.js file

console.log('calling form parent process');