当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js process.send()用法及代码示例


process.send()方法是流程模块的内置应用程序编程接口,子流程用于与父流程进行通信。此方法不适用于根进程,因为它没有任何父进程。

用法:

process.send(message, [sendHandle])

参数:此方法接受以下参数:

  • message:必须发送的消息。
  • sendHandle:套接字或服务器对象。它是一个可选参数。

返回值:布尔值。如果邮件发送成功,则返回true,否则返回false。

范例1:首先,在Parent.js中,我们产生子进程。然后开始收听子进程。在Child.js中,我们在Child.js中获得消息。然后,我们检查send方法是否可用,然后使用process.send()向父级发送一条消息。



Parent.js


// Require fork method from child_process 
// to spawn child process
const fork = require('child_process').fork;
  
// Child process file
const child_file = 'Child.js';
  
// Spawn child process
const child = fork(child_file);
  
// Start listening to the child process
child.on('message', message => {
  
    // Message from the child process
    console.log('Message from child:', message);
});

Child.js


console.log('In Child.js')
  
// If the send method is available
if(process.send) {
  
    // Send Hello
    process.send("Hello, this is child process.");
}

使用以下命令运行Parent.js文件:

node Parent.js

输出:

In Child.js
Message from child:Hello, this is child process.

范例2:来自子进程的多条消息。

Parent.js


// Require fork method from child_process 
// to spawn child process
const fork = require('child_process').fork;
  
// Child process file
const child_file = 'Child.js';
  
// Spawn child process
const child = fork(child_file);
  
// Start listening to the child process
child.on('message', message => {
  
    // Message from the child process
    console.log('Message from child:', message);
});

Child.js


console.log('In Child.js')
  
// If the send method is available
if(process.send) {
  
    // Send Hello
    process.send("Hello, this is child process.");
  
    // Send multiple messages
    setTimeout((function() {
        return process.send("This was send after 1 second.");
    }), 1000);
  
    setTimeout((function() {
        return process.send("This was send after 2 seconds.");
    }), 2000);
  
    setTimeout((function() {
        return process.send("This was send after 3 seconds.");
    }), 3000); 
}

使用以下命令运行Parent.js文件:

node Parent.js

输出:

In Child.js
Message from child:Hello, this is child process.
Message from child:This was sent after 1 second.
Message from child:This was sent after 2 seconds.
Message from child:This was sent after 3 seconds.

参考: https://nodejs.org/api/process.html#process_process_send_message_sendhandle_options_callback

相关用法


注:本文由纯净天空筛选整理自adityapande88大神的英文原创作品 Node.js process.send() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。