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


Node.js MessageChannel.postMessage()用法及代碼示例

MessagePort.postMessage()方法是worker_threads模塊內的Worker類的內置應用程序編程接口,用於將消息從一個端口發送到另一個端口。

用法:

const MessagePort.postMessage(value[, transferList])

參數:此方法將值作為參數可以包含任何類型的對象。

返回值:此方法將消息從一個端口發送到另一個端口。

範例1: 文件名:index.js



Javascript

// Node.js program to demonstrate the 
// MessageChannel.postMessage() method 
  
// Importing worker_thread module 
const { MessageChannel, receiveMessageOnPort } 
        = require('worker_threads'); 
  
// Creating and initializng the MessageChannel 
const { port1, port2 } = new MessageChannel(); 
  
// Sending data to port 2 
// by using postMessage() method 
port1.postMessage({ hello:'world1' }); 
  
// Posting data in port 1 
// by using postMessage() method 
port2.postMessage({ hello:'world2' }); 
  
/// Display the result 
console.log("recived data in port1:"); 
console.log(receiveMessageOnPort(port1)); 
  
console.log("recived data in port2:"); 
console.log(receiveMessageOnPort(port2)); 
  
// Closing the ports 
port1.close(); 
port2.close();

輸出:

recived data in port1:
{ message:{ hello:'world2' } }
recived data in port2:
{ message:{ hello:'world1' } }

範例2: 文件名:index.js

Javascript

// Node.js program to demonstrate the 
// MessageChannel.postMessage() method 
  
// Importing worker_thread module 
  
const { MessageChannel, receiveMessageOnPort }  
        = require('worker_threads'); 
  
// Creating and initializng the MessageChannel 
const { port1, port2 } = new MessageChannel(); 
  
// Catching the event message 
port2.on('message', (message) => console.log(message)); 
  
// Catching the event close 
port2.on('close', () => console.log('closed!')); 
  
// Sending message to port2 
// by using postMessage() method 
port1.postMessage('GFG'); 
  
// Closing port by using 
// close() method 
port1.close();

輸出:

GFG
closed!

使用以下命令運行index.js文件:

node index.js

參考: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist

相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node.js MessageChannel.postMessage() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。