Node.js – process.channel 属性

node.jsserver side programmingprogramming

当一个 Node 进程创建时,如果该进程带有 IPC 通道,则 process.channel 属性会提供对该 IPC 通道的引用。如果不存在 IPC 通道,则此属性未定义。

语法

process.channel

示例 1

创建两个文件 "channel.js""util.js",并复制以下代码片段。创建文件后,使用命令 "nodechannels.js""nodeutil.js" 运行代码。

channel.js

// process.channel 属性演示示例

// 导入进程模块
const cp = require('child_process');

// 获取子进程的引用
const process = cp.fork(`${__dirname}/util.js`);

// 向子进程发送以下消息
process.send({ msg: 'Welcome to Tutorials Point' });

console.log(process.channel)

util.js

// 此子进程将通过通道消费消息
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 Tutorials Point' }

示例 2

我们再看一个例子。

// process.channel 属性演示示例

// 导入进程模块
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

相关文章