Search code examples
node.jsexpresschild-process

Node child_process pass argv when forked


I have Node application with Express server. I also have node scripts in server folder. During some events I need get data from separate node scripts, so I create child process.

Without arguments, everything works fine, but I need to pass some data from parent process.

var express = require('express');
var router = express.Router();
var child_process = require('child_process');

router.get('/:site/start', function(req, res, next) {
        const basedir = req.app.get('basedir');
        const child_script_path = basedir + '/scripts/script.js';
        const child_argv = [
            '--slowmo=0',
            '--headless=1'
        ];

        child = child_process.fork(child_script_path, {
            execArgv: child_argv
        });

        ...
    }
});

When I try to pass arguments and run script through Express, these errors are shown:

/home/user/.nvm/versions/node/v8.9.4/bin/node: bad option: --slowmo=0
/home/user/.nvm/versions/node/v8.9.4/bin/node: bad option: --headless=1

But when I run script from command line like :

node /scripts/script.js --slowmo=0 --headless=1

I get no errors and script can catch args from command line.

How can I pass args to child script in this situation?

Ubuntu 16.04
Node 8.9.4
Express 4.15.5


Solution

  • execArgv option is used to pass arguments for the execution process, not for your script.
    This could be useful for passing specific execution environment to your forked process.

    If you want to pass arguments to your script, you should use args.
    child_process.fork(modulePath[, args][, options])

    Example:

    const child_process = require('child_process');
    
    const child_script_path = './script.js';
    const child_argv = [
      '--foo',
      '--bar'
    ]
    const child_execArgv = [
      '--use-strict'
    ]
    
    let child = child_process.fork(child_script_path, child_argv, {
      execArgv: child_execArgv  // script.js will be executed in strict mode
    })
    
    // script.js
    console.log(process.argv[2], process.argv[3])  // --foo --bar