简体   繁体   中英

How can I call a different Node.js script from my own?

I am building an application that bundles several CLI apps together using Node.js for internal use. I'm using several NPM dependencies, and some of those have their own binaries for CLI commands.

For user friendliness, I'm using Commander 's git-style sub-commands for my own application. The module requires there to be a separate .js file for each of the sub-commands that act as binaries.

This is similar to what I have so far, and what I'm trying to accomplish:

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

So basically I'm trying to wrap another binary within my own. This method works, but it feels somewhat hack-ish and it opens 2 instances of Node.exe .

You can use 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.

or if you don't want to spawn new NodeJS process, you can use vm module: https://nodejs.org/api/vm.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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