当节点进程与 IPC 通道一起生成时, process.channel 属性提供对该 IPC 通道的引用。如果不存在 IPC 通道,则此属性未定义。
process.channel
创建两个文件“channel.js”和“util.js”并复制以下代码片段。创建文件后,使用命令“node channels.js”和“node util.js”来运行代码。
//process.channelProperty 演示示例 // 导入流程模块 const cp = require('child_process'); // 得到孩子的参考 const process = cp.fork(`${__dirname}/util.js`); // 发送以下消息给孩子 process.send({ msg: 'Welcome to nhooo.com' }); console.log(process.channel)
// 这个孩子将通过渠道消费消息 process.on('message', (m) => { console.log('CHILD got message:', m); process.exit() });输出结果
Pipe { buffering: false, pendingHandle: null, onread: [Function], sockets: { got: {}, send: {} } } CHILD got message: { msg: 'Welcome to nhooo.com' }
让我们再看一个例子。
//process.channelProperty 演示示例 // 导入流程模块 const process = require('process'); // 检查进程通道 if(process.channel) console.log("Process Channel exist") else console.log("Process Channel doesn't exist")输出结果
Process Channel doesn't exist