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
const cp = require( 'child_process' );
const process = cp.fork(`${__dirname}/sub.js`);
process.send({ hello: 'world' });
|
Here the file name is sub.js
Javascript
const process = require( 'process' );
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
const cp = require( 'child_process' );
const process = cp.fork(`${__dirname}/sub.js`);
process.on( 'message' , (m) => {
console.log( 'PARENT got message:' , m);
});
process.send({ hello: 'world' });
|
Here the filename is sub.js
Javascript
const process = require( 'process' );
process.on( 'message' , (m) => {
console.log( 'CHILD got message:' , m);
process.exit(0)
});
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...