【问题标题】:How do I run a Node.js script from within another Node.js script如何从另一个 Node.js 脚本中运行 Node.js 脚本
【发布时间】:2014-05-04 00:41:27
【问题描述】:

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

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

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

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

感谢您的帮助!!

【问题讨论】:

  • 你考虑过 var exec = require('child_process').exec; exec('node /compile.js', ...) ?
  • 为什么不简单地 require() 呢?
  • @dandavis,“Compile.js 目前不导出任何方法。”
  • @dandavis 我实际上认为 require 可能会起作用,除了脚本正在进行异步操作。也许有一个带有回调的 require 版本?

标签: javascript node.js


【解决方案1】:

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

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

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

【讨论】:

  • 如果你想在你调用的节点 js 脚本中添加参数: var process = childProcess.fork(scriptPath, ['arg1', 'arg2']);
  • 如果您想为简单的任务同步运行,您还可以使用child_process.execFileSync(file[, args][, options])。见nodejs.org/api/…
  • exit 没有被触发,即使我在子进程上执行process.exit(0)。有什么想法吗?
【解决方案2】:

将此行放在 Node 应用程序的任何位置。

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

在 some_code.js 文件中

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

【讨论】:

  • 终于有一个简单而简短的回答了!!谢谢!
【解决方案3】:

分叉一个子进程可能有用,请参阅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' });

现在,子进程会像......同样来自示例:

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

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

但要完成简单的任务,我认为创建一个扩展 events.EventEmitter 类的模块就可以了...http://nodejs.org/api/events.html

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多