Passing node flags/args to child process

前端 未结 1 517
一生所求
一生所求 2021-02-14 05:29

If we fork a child_process in Node, how can we pass node parameters to the child_process?

https://nodejs.org/api/child_process.html

Specifically I would like to

相关标签:
1条回答
  • 2021-02-14 05:52

    You'll need to set the execArgv option to fork.

    If you don't, you'll get the same option as the node process you're 'forking' (it actually is just a spawn, not a POSIX-fork).

    So you could do something like this:

    var n = cp.fork(modname, {execArgv: ['--harmony']});
    

    If you want to pass on the node-options from the parent:

    var n = cp.fork(modname, {execArgv: process.execArgv.concat(['--harmony'])}
    

    Warning: child_process has a safeguard against the -e switch that you are circumventing with that! So don't do this from the command line with an -e or -p. You will be creating a new process with a script that is the same as that from the parent – a fork bomb.

    If you still want to be able to pass on options to fork via the environment, you could do something like this:

    var cp = require('child_process');
    var opts = Object.create(process.env);
    opts.execArgv = ['--harmony'];
    
    var n = cp.fork(filePath, opts);
    

    Another option may be to alter process.execArgv (like process.execArgv.push('--harmony')) but I am pretty sure that is a bad idea and might result in strange behaviour elswhere.

    0 讨论(0)
提交回复
热议问题