Using this IPC is set up by default between parent node process and child node process:
const cp = require('child_process');
const k = cp.fork(childPath);
I can send a message to the child process:
k.send('foobar');
and received a message back:
k.on('message', m => console.log('received a message from child:',m));
however, my question is - is there a way to set-up IPC with a node.js child process using cp.spawn instead of cp.fork?
There is no built-in way to pass in messages to the child process using the EventEmitter
framework when you use spawn
. This is exactly the purpose of fork
, and what makes it different from spawn
.
See the snippet below from the official docs:
The child_process.fork() method is a special case of child_process.spawn() used specifically to spawn new Node.js processes. Like child_process.spawn(), a ChildProcess object is returned. The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child. See subprocess.send() for details.
There could possibly be an option to poke with a custom wrap over spawn
to "augment" its capability to use EventEmitter
, but I don't see a reason why one wouldn't just use fork
for its intended use-case instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With