Skip to content
Related Articles

Related Articles

Improve Article

Node.js Process message Event

  • Last Updated : 07 Aug, 2021

The ‘message’ is an event of class Process within the process module which is emitted whenever a message sent by a parent process using childprocess.send() is received by the child process.

Syntax:

Event: 'message'

Parameters: This event does not accept any argument as a parameter.

Return Value: This event returns nothing but a callback function for further operation.  

Example 1:



The filename is index.js

Javascript




// Node.js program to demonstrate the 
// Process 'message' Event
 
// Importing process module
const cp = require('child_process');
 
// Initiating child process
const process = cp.fork(`${__dirname}/sub.js`);
 
// Causes the child to print:
// CHILD got message: { hello: 'world' }
process.send({ hello: 'world' });

Here the file name is sub.js

Javascript




// Importing process module
const process = require('process');
 
// Message Event
process.on('message', (m) => {
    console.log('CHILD got message:', m);
    process.exit(0)
});

 
Run the index.js file using the following command:

node index.js

Output:

CHILD got message: { hello: 'world' }

Example 2:

The filename is index.js

Javascript




// Node.js program to demonstrate the 
// Process 'message' Event
 
// Importing process module
const cp = require('child_process');
 
// Initiating child process
const process = cp.fork(`${__dirname}/sub.js`);
 
// Message Event
process.on('message', (m) => {
    console.log('PARENT got message:', m);
});
 
// Causes the child to print:
// CHILD got message: { hello: 'world' }
process.send({ hello: 'world' });

Here the filename is sub.js

Javascript




// Importing process module
const process = require('process');
 
// Message Event
process.on('message', (m) => {
    console.log('CHILD got message:', m);
    process.exit(0)
});
 
// Causes the parent to print:
// PARENT got message: { foo: 'bar', baz: null }
process.send({ foo: 'bar', baz: NaN });

Run the index.js file using the following command:

node index.js

Output:

CHILD got message: { hello: 'world' }
PARENT got message: { foo: 'bar', baz: null }

Reference: https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_message
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :