推荐答案
在 Node.js 中,父进程和子进程之间的通信可以通过 child_process 模块来实现。具体来说,可以使用 fork() 方法创建子进程,并通过 send() 和 message 事件来实现进程间的通信。
父进程代码示例
// www.javascriptcn.com code example
const { fork } = require('child_process');
// 创建子进程
const child = fork('child.js');
// 向子进程发送消息
child.send({ message: 'Hello from parent' });
// 监听子进程的消息
child.on('message', (message) => {
console.log('Message from child:', message);
});子进程代码示例
// 监听父进程的消息
process.on('message', (message) => {
console.log('Message from parent:', message);
// 向父进程发送消息
process.send({ message: 'Hello from child' });
});本题详细解读
1. fork() 方法
fork() 是 child_process 模块中的一个方法,用于创建一个新的 Node.js 进程。与 spawn() 和 exec() 不同,fork() 专门用于创建 Node.js 子进程,并且会自动建立一个通信通道,使得父子进程可以通过 send() 和 message 事件进行通信。
2. send() 方法
send() 方法用于向子进程或父进程发送消息。消息可以是任何可序列化的 JavaScript 对象。在父进程中,send() 方法通过子进程对象调用;在子进程中,send() 方法通过 process 对象调用。
3. message 事件
message 事件用于接收来自另一个进程的消息。在父进程中,可以通过子进程对象监听 message 事件;在子进程中,可以通过 process 对象监听 message 事件。
4. 通信流程
- 父进程通过
fork()创建子进程。 - 父进程通过
send()方法向子进程发送消息。 - 子进程通过
process.on('message')监听父进程的消息,并通过process.send()向父进程发送消息。 - 父进程通过
child.on('message')监听子进程的消息。
通过这种方式,父进程和子进程可以实现双向通信,适用于需要多进程协作的场景。