如何调用与我自己不同的 Node.js 脚本?
How can I call a different Node.js script from my own?
我正在构建一个应用程序,它使用 Node.js 将多个 CLI 应用程序捆绑在一起供内部使用。我正在使用几个 NPM 依赖项,其中一些有自己的 CLI 命令二进制文件。
为了用户友好,我将 Commander
's git-style sub-commands 用于我自己的应用程序。该模块要求每个作为二进制文件的子命令都有一个单独的 .js
文件。
这与我目前所拥有的以及我正在努力实现的目标相似:
var program = require('commander'),
spawn = require('child_process').spawn;
program.parse(process.argv);
var args = ['./node_modules/exampleDep/.bin/index.js'].push(program.args);
var wrap = spawn('node', args);
wrap.stdout.on('data', function (data) {
process.stdout.write(data);
});
wrap.stderr.on('data', function (data) {
process.stderr.write(data);
});
所以基本上我是在尝试将另一个二进制文件包装在我自己的二进制文件中。此方法有效,但感觉有点 hack-ish,它会打开 Node.exe
.
的 2 个实例
您可以使用 child_process.fork
:https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options
This is a special case of the child_process.spawn() functionality for spawning Node.js processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See [child.send(message, [sendHandle])][] for details.
或者如果你不想生成新的 NodeJS 进程,你可以使用 vm
模块:
https://nodejs.org/api/vm.html
我正在构建一个应用程序,它使用 Node.js 将多个 CLI 应用程序捆绑在一起供内部使用。我正在使用几个 NPM 依赖项,其中一些有自己的 CLI 命令二进制文件。
为了用户友好,我将 Commander
's git-style sub-commands 用于我自己的应用程序。该模块要求每个作为二进制文件的子命令都有一个单独的 .js
文件。
这与我目前所拥有的以及我正在努力实现的目标相似:
var program = require('commander'),
spawn = require('child_process').spawn;
program.parse(process.argv);
var args = ['./node_modules/exampleDep/.bin/index.js'].push(program.args);
var wrap = spawn('node', args);
wrap.stdout.on('data', function (data) {
process.stdout.write(data);
});
wrap.stderr.on('data', function (data) {
process.stderr.write(data);
});
所以基本上我是在尝试将另一个二进制文件包装在我自己的二进制文件中。此方法有效,但感觉有点 hack-ish,它会打开 Node.exe
.
您可以使用 child_process.fork
:https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options
This is a special case of the child_process.spawn() functionality for spawning Node.js processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See [child.send(message, [sendHandle])][] for details.
或者如果你不想生成新的 NodeJS 进程,你可以使用 vm
模块:
https://nodejs.org/api/vm.html