为什么Node父进程使用subprocess on message事件来处理子进程发送的消息

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

这是来自 nodejs 文档的示例。

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 });

我可以理解子进程使用 process.on('message'...)process.send(..) 来接收和向父进程发送消息。

但是为什么父进程要使用子进程的实例来接收来自子进程的消息n.on('message'....)。应该和子进程一样process.on('message'...)吗?

谢谢。

parent会和很多child人交流。而 child 将与一个 parent.

通信