Node.js MessageChannel.close() Method
Last Updated :
12 Jul, 2021
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
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();
|
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
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();
|
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
Please Login to comment...