Node.js MessageChannel.postMessage() Method
Last Updated :
01 Feb, 2023
The MessageChannel.postMessage() method is an inbuilt application programming interface of class Worker within worker_threads module which is used to send the message from one port to another.
Syntax:
const MessageChannel.postMessage(value[, transferList])
Parameters: This method takes the value as a parameter which can contain any kind of object.
Return Value: This method sends the message from one port to another.
Example 1: Filename: index.js
Javascript
const { MessageChannel, receiveMessageOnPort }
= require( 'worker_threads' );
const { port1, port2 } = new MessageChannel();
port1.postMessage({ hello: 'world1' });
port2.postMessage({ hello: 'world2' });
console.log( "received data in port1 : " );
console.log(receiveMessageOnPort(port1));
console.log( "received data in port2 : " );
console.log(receiveMessageOnPort(port2));
port1.close();
port2.close();
|
Output:
received data in port1 :
{ message: { hello: 'world2' } }
received data in port2 :
{ message: { hello: 'world1' } }
Example 2: Filename: index.js
Javascript
const { MessageChannel, receiveMessageOnPort }
= require( 'worker_threads' );
const { port1, port2 } = new MessageChannel();
port2.on( 'message' , (message) => console.log(message));
port2.on( 'close' , () => console.log( 'closed!' ));
port1.postMessage( 'GFG' );
port1.close();
|
Output:
GFG
closed!
Run the index.js file using the following command:
node index.js
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist
Share your thoughts in the comments
Please Login to comment...