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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。