Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up IPC using spawn instead of fork

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?

like image 822
Alexander Mills Avatar asked Sep 04 '25 01:09

Alexander Mills


1 Answers

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.

like image 129
Rodrigo Rodrigues Avatar answered Sep 07 '25 00:09

Rodrigo Rodrigues