Open In App

Node.js Process disconnect Event

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss about the disconnect event of the Process object. The disconnect event will be issued when the IPC channel is closed if the Node.js process was started using an IPC channel.

Syntax:

process.on('disconnect', () => {
    // Disconnect event
});

The below examples illustrate the use of the Process disconnect event property in Node.js:

Example 1:

Filename: parent.js

Javascript




// 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);


Filename: child.js

Javascript




console.log('In child.js')
  
if (process.connected) {
    console.log("Child Process connected!")
    console.log("Disconnecting in 3000ms")
    setTimeout(() => {
        process.disconnect();
    }, 3000);
}
  
process.on('disconnect', () => {
    console.log("Child Process disconnected!")
});


Output:

In child.js
Child Process connected!
Disconnecting in 3000ms 
Child Process disconnected!

Example 2:

Filename: parent.js

Javascript




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


Filename: child2.js

Javascript




console.log("In Child Process!")
  
process.disconnect()
  
process.on('disconnect', () => {
    console.log(`Child process disconnected`);
});


Output:

In Child Process!
Child process disconnected

Reference: https://nodejs.org/api/process.html#event-disconnect



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads