Jonah
Jonah

Reputation: 1545

Sending objects as parameters to forked nodejs processes

Having fork('./MyProcess.js',['foo']); in the main process and console.log(process.argv[2]); in the forked process will log foo to my console.

However, fork('./MyProcess.js',[{myProp : 'bar'}]); in the main process and console.log(process.argv[2]); console.log(process.argv[2].myProp); in the forked process will log [object Object] (as expected) but undefined for the second log.

Why is this, and what should I do to get the desired behavior?

Upvotes: 4

Views: 12270

Answers (4)

Pål Thingbø
Pål Thingbø

Reputation: 11

You can base64 encode your object:

const obj = { foo: 'bar', date: new Date() };
const encoded = Buffer.from(JSON.stringify(obj)).toString('base64');

fork('./MyProcess.js',[encoded]);

On the receiving end:

const data = process.argv[2];
const decoded = JSON.parse(
  Buffer.from(data, 'base64').toString('utf-8')
);

Upvotes: 1

ryanhex53
ryanhex53

Reputation: 727

Choice No.5, It's much better to set a KEY VALUE pair in env option.

// in parent process
fork('./some.js', {
  env: Object.assign(process.env, { HELLO: 'world' })
});
// in forked process <some.js>
console.log(process.env.HELLO);
// world

Upvotes: 1

tangxinfa
tangxinfa

Reputation: 1510

Pass object(json) to child process through commadline arguments is not a good idea, command arguments need escape first(not easy). You have some choice:

  1. hex encode the json then pass to child process, this works but your child process interface is bad.
  2. save json to a file, pass the file path instead.
  3. pass the json to child process through stdin.
  4. send the json as message to child process, see https://nodejs.org/api/child_process.html#child_process_child_send_message_sendhandle_options_callback

Upvotes: 7

E_net4
E_net4

Reputation: 30013

As stated in the documentation of child_process.fork:

child_process.fork(modulePath[, args][, options])

args List of string arguments

By doing fork('./MyProcess.js',[{myProp : 'bar'}]), you are passing an object where a string was expected. The resulting behaviour might become implementation dependent, but my trial on Node.js v6.1.0 shows that the object would be converted to the string '[object Object]'. The string will not have the myProp property, thus yielding undefined.

The solution is to pass strings only:

fork('./MyProcess.js', ['bar']);

If you care about named parameters, simply format them appropriately (see below), then parse them with another package (such as yargs) or a solution of your own. In this case, you could do this:

fork('./MyProcess.js', ['--myProp=bar']);

For completeness, you could have this in "MyProcess.js":

var argv = require('yargs').argv;
console.log('My prop is: ' + argv.myProp);

Upvotes: 4

Related Questions