Open In App

Node.js MessageChannel.close() Method

Last Updated : 12 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The MessageChannel.close() method is an inbuilt application programming interface of class Worker within worker_threads module which is used to disable the object of message port for sending the further message.

Syntax:

const MessageChannel.close()

Parameters: This method does not accept any parameter.

Return Value: This method does not return any value.

Example 1: Filename: index.js 
 

javascript




// Node.js program to demonstrate the
// MessageChannel.close() method
 
// Importing worker_thread module
const { MessageChannel, receiveMessageOnPort }
        = require('worker_threads');
 
// Creating and initializing the MessageChannel
const { port1, port2} = new MessageChannel();
 
// Posting data in port1
port1.postMessage({ hello: 'world1' });
 
// Posting data in port2
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();


Run the index.js file using the following command: 
 

node index.js

 

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.close() 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
port1.postMessage('GFG');
 
// Closing port by using close() method
port1.close();


Run the index.js file using the following command: 
 

node index.js

 

Output:

 

GFG
closed!

 

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_port_close

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads