Node.js process.send() Method
The process.send() method is an inbuilt application programming interface of the process module which is used by the child process to communicate with the parent process. This method does not work for the root process because it does not have any parent process.
Syntax:
process.send(message, [sendHandle])
Parameters: This method accepts the following parameter:
- message: The message that has to be sent.
- sendHandle: A Socket or Server object. It is an optional parameter.
Return Value: Boolean value. Returns true if the message was sent successfully else returns false.
Example 1: First, in Parent.js, we spawn the child process. Then start listening to the child process. In Child.js, we get the message in Child.js. Then we check if send method is available and then send a message to the parent using process.send().
Parent.js
const fork = require( 'child_process' ).fork;
const child_file = 'Child.js' ;
const child = fork(child_file);
child.on( 'message' , message => {
console.log( 'Message from child:' , message);
});
|
Child.js
console.log( 'In Child.js' )
if (process.send) {
process.send( "Hello, this is child process." );
}
|
Run Parent.js file using the below command:
node Parent.js
Output:
In Child.js
Message from child: Hello, this is child process.
Example 2: Multiple messages from the child process.
Parent.js
const fork = require( 'child_process' ).fork;
const child_file = 'Child.js' ;
const child = fork(child_file);
child.on( 'message' , message => {
console.log( 'Message from child:' , message);
});
|
Child.js
console.log( 'In Child.js' )
if (process.send) {
process.send( "Hello, this is child process." );
setTimeout(( function () {
return process.send( "This was send after 1 second." );
}), 1000);
setTimeout(( function () {
return process.send( "This was send after 2 seconds." );
}), 2000);
setTimeout(( function () {
return process.send( "This was send after 3 seconds." );
}), 3000);
}
|
Run Parent.js file using the below command:
node Parent.js
Output:
In Child.js
Message from child: Hello, this is child process.
Message from child: This was sent after 1 second.
Message from child: This was sent after 2 seconds.
Message from child: This was sent after 3 seconds.
Reference: https://nodejs.org/api/process.html#process_process_send_message_sendhandle_options_callback
Last Updated :
18 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...