Node.js Process message Event
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 moduleconst cp = require('child_process');// Initiating child processconst 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 moduleconst process = require('process');// Message Eventprocess.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 moduleconst cp = require('child_process');// Initiating child processconst process = cp.fork(`${__dirname}/sub.js`);// Message Eventprocess.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 moduleconst process = require('process');// Message Eventprocess.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


