Reputation: 1545
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
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
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
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:
Upvotes: 7
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