當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。