Node.js process.disconnect() Method
Last Updated :
25 May, 2021
The process.disconnect() property is an inbuilt application programming interface of the process module which is used by the child process to disconnect from the parent process. This method does not work for the root process because it does not have any parent process.
Syntax:
process.disconnect()
Parameters: It does not take any parameters.
Return Value: It does not have a return value.
Example 1: In Parent.js, we spawn the child process. In Child.js, we get the message In Child.js. Then if the process.connected is true then print a message on the console and disconnect.
Parent.js
const fork = require( 'child_process' ).fork;
const child_file = 'Child.js' ;
const child = fork(child_file);
|
Child.js
console.log( 'In Child.js' )
if (process.connected) {
if (process.connected == true ) {
console.log( "Child.js is connected." );
}
process.disconnect();
if (process.connected == false ) {
console.log( "Child.js has been disconnected." );
}
}
|
Run Parent.js using the below command:
node Parent.js
Output:
In Child.js
Child.js is connected.
Child.js has been disconnected.
Example 2: Disconnect after some time. Notice that no message will print after the disconnect function runs.
Parent.js
const fork = require( 'child_process' ).fork;
const child_file = 'Child.js' ;
const child = fork(child_file);
|
Child.js
console.log( 'In Child.js' )
if (process.connected) {
setTimeout(( function () {
if (process.connected == true ) {
console.log( "This was sent after 1 second." );
}
}), 1000);
setTimeout(( function () {
if (process.connected == true ) {
console.log( "This was sent after 2 seconds." );
}
}), 2000);
setTimeout(( function () {
process.disconnect();
}), 2500);
setTimeout(( function () {
if (process.connected == true ) {
console.log( "This was sent after 3 seconds." );
}
}), 3000);
}
|
Run Parent.js using the below command:
node Parent.js
Output:
In Child.js
Message from child: This was sent after 1 second.
Message from child: This was sent after 2 seconds.
Reference: https://nodejs.org/api/process.html#process_process_disconnect
Share your thoughts in the comments
Please Login to comment...