klabe
klabe

Reputation: 505

Why does Node parent process use the subprocess on message event to handle messages sent by child process

Here's the example from the nodejs document.

parent.js

const cp = require('child_process');
const n = cp.fork(`${__dirname}/sub.js`);

n.on('message', (m) => {
  console.log('PARENT got message:', m);
}); // Why use n the subprocess here????

// Causes the child to print: CHILD got message: { hello: 'world' }
n.send({ hello: 'world' });

child.js

process.on('message', (m) => {
  console.log('CHILD got message:', m);
});

// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
process.send({ foo: 'bar', baz: NaN });

I can understand the child process uses process.on('message'...) and process.send(..) to receive and send messages to the parent process.

But why does the parent process to use an instance of the subprocess to receive messages from the child process n.on('message'....). Should it be process.on('message'...) just like the child process?

Thank you.

Upvotes: 1

Views: 304

Answers (1)

Ahmed ElMetwally
Ahmed ElMetwally

Reputation: 2383

The parent will communicate with many children. while child will communicate with one parent.

Upvotes: 1

Related Questions