Node.js MessageChannel.postMessage() Method

Last Updated : 1 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
// Node.js program to demonstrate the
// MessageChannel.postMessage() method

// Importing worker_thread module
const { MessageChannel, receiveMessageOnPort }
        = require('worker_threads');

// Creating and initializing 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("received data in port1 : ");
console.log(receiveMessageOnPort(port1));

console.log("received data in port2 : ");
console.log(receiveMessageOnPort(port2));

// Closing the ports
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
// Node.js program to demonstrate the
// MessageChannel.postMessage() method

// Importing worker_thread module

const { MessageChannel, receiveMessageOnPort } 
        = require('worker_threads');

// Creating and initializing 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();

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

Comment

Explore