Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - how to get spawned child to communicate with parent?

I'm trying this out:

var child = spawn('node', args, {cwd: parentDir, stdio: 'ipc'} );

(args is an array of parameters)

but it gives the following error:

TypeError: Incorrect value of stdio option: ipc

This actually works, so the problem seems indeed to be the stdio ipc parameter:

var child = spawn('node', args, {cwd: parentDir} );

This also works:

 var child = spawn('node', args, {cwd: parentDir, stdio: 'pipe'} );

I read this: http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options but I don't see where I am going wrong. This is the first time I try to use this NodeJS functionality so I am sorry if the problem is evident.

Maybe there is some other way to solve the problem. The child has to be spawned and not forked and I simply want to be able to send messages from the child to the parent.

Thank you!!

EDIT: I have Node v0.8.18. I searched version history for IPC http://nodejs.org/changelog.html and there's nothing with search term "IPC" that makes me think that I need a newer version of NodeJS.

like image 462
rockamic Avatar asked Jan 24 '14 22:01

rockamic


2 Answers

Rockamic answered his own question, based on a couple of my nudges. Here's what worked & why:

 var child = spawn('node', args, {cwd: parentDir, stdio: [null, null, null, 'ipc']} );

specifying stdin, stdout, stderr, as null indicates default...

If rockamic comes back and provides his own answer, I will gladly delete this so he can get the accepted answer.

like image 165
bellasys Avatar answered Nov 07 '22 23:11

bellasys


Here's a full example, slightly different from the other answers:

parent.js

spawn('node', ['child.js'], {
    stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
}).on('message', function(data) {
    console.log(data);
});
  • Child shares same cwdas the parent.
  • inherit is used to share the same streams (like stdout) with the child, so you can see stuff in your console for example.

child.js

process.send && process.send('hello parent');
  • If you're going to use the same code directly, the function won't be available (it'll be undefined), so you need to check first.
like image 28
Hanuman Avatar answered Nov 07 '22 23:11

Hanuman