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