Skip to content
Related Articles

Related Articles

Improve Article

Node.js process.disconnect() Method

  • Last Updated : 25 May, 2021
Geek Week

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




// Require fork method from child_process 
// to spawn child process
const fork = require('child_process').fork;
  
// Child process file
const child_file = 'Child.js';
  
// Spawn child process
const child = fork(child_file);

Child.js




console.log('In Child.js')
  
// If the send method is available
if (process.connected) {
  
    // Check if its connected or not
    if (process.connected == true) {
        console.log("Child.js is connected.");
    }
  
    // Use process.disconnect() to disconnect
    process.disconnect();
  
    // Check if its connected or not
    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




// Require fork method from child_process 
// to spawn child process
const fork = require('child_process').fork;
  
// Child process file
const child_file = 'Child.js';
  
// Spawn child process
const child = fork(child_file);

Child.js




console.log('In Child.js')
  
// If the send method is available
if (process.connected) {
  
    // Send multiple messages
    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);
  
    // Disconnect after 2.5 seconds
    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




My Personal Notes arrow_drop_up
Recommended Articles
Page :