如何从另一个Node.js脚本中运行Node.js脚本 [英] How do I run a Node.js script from within another Node.js script

查看:327
本文介绍了如何从另一个Node.js脚本中运行Node.js脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 compile.js 的独立节点脚本。它位于一个小型Express应用程序的主文件夹中。

I have a standalone Node script called compile.js. It is sitting inside the main folder of a small Express app.

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

Sometimes I will run the compile.js script from the command line. In other scenarios, I want it to be executed by the Express app.

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

Both scripts load config data from the package.json. Compile.js does not export any methods at this time.

加载此文件的最佳方法是什么并执行它?我查看了 eval() vm.RunInNewContext require ,但不确定什么是正确的方法。

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.

感谢您的帮助!!

推荐答案

您可以使用子进程来运行脚本,并侦听退出和错误事件,以了解进程何时完成或出错(在某些情况下可能导致退出事件未触发) )。此方法的优点是可以使用任何异步脚本,甚至是那些未明确设计为作为子进程运行的脚本,例如您要调用的第三方脚本。示例:

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

请注意,如果在可能存在安全问题的环境中运行第三方脚本,则可能更为可取在沙盒vm上下文中运行脚本。

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.

这篇关于如何从另一个Node.js脚本中运行Node.js脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆