简体   繁体   English

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

[英]How do I run a Node.js script from within another Node.js script

I have a standalone Node script called compile.js .我有一个名为compile.js的独立节点脚本。 It is sitting inside the main folder of a small Express app.它位于一个小型 Express 应用程序的主文件夹内。

Sometimes I will run the compile.js script from the command line.有时我会从命令行运行compile.js脚本。 In other scenarios, I want it to be executed by the Express app.在其他场景中,我希望它由 Express 应用程序执行。

Both scripts load config data from the package.json .两个脚本都从package.json加载配置数据。 Compile.js does not export any methods at this time. Compile.js不导出任何方法。

What is the best way to load up this file and execute it?加载此文件并执行它的最佳方法是什么? I have looked at eval() , vm.RunInNewContext , and require , but not sure what is the right approach.我看过eval()vm.RunInNewContextrequire ,但不确定什么是正确的方法。

Thanks for any help!!谢谢你的帮助!!

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.请注意,如果在可能存在安全问题的环境中运行第三方脚本,则最好在沙盒 vm 上下文中运行该脚本。

Put this line in anywhere of the Node application.将此行放在 Node 应用程序的任何位置。

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

In some_code.js file在 some_code.js 文件中

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

Forking a child process may be useful, see http://nodejs.org/api/child_process.html分叉子进程可能很有用,请参阅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但是为了做简单的任务,我认为创建一个扩展 events.EventEmitter 类的模块会做... http://nodejs.org/api/events.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM