基础核心:
1.child_prcess.spawn(command, [args], { stdio: [null, null, null, 'ipc'} ) 创建一个有 ipc 通道的子进程
2.childProcess.send() 向发送消息
3.childProcess.on('message', message =>{}) 接受子进程发送过来的消息
4.process.send() 子进程向 父进程发送消息;
5.process.on('message', message =>{}) 子进程接受父进程发送过来的消息
parent.js
const child_process = require('child_process')
const childProcess = child_process.spawn('node', ['test.js'], {stdio: [null, null, null, 'ipc']})
// 监听标准输出
childProcess.stdout.on('data', chunk => {
console.log(new TextDecoder().decode(chunk))
})
// 监听 IPC 通道
childProcess.on('message', message => {
console.log('父进程接收到到子进程发送过来的消息: ', message)
})
// 通过 IPC 通过到发送消息
childProcess.send('父进程向子进程发送的消息')
child.js
// 通过 IPC 通道接受消息
process.on('message', message => {
console.log('子进程接收到了 父进程发送过来的消息: ', message)
// 通过 IPC 通道发送消息
process.send('子进程发送的消息')
// 断开 ipc 通道
process.disconnect()
})