Node.js 进程断开连接事件
在本文中,我们将讨论Process对象的 断开连接事件 。如果使用IPC通道启动了Node.js进程,当IPC通道关闭时,将发出 断开连接 事件。
语法:
process.on('disconnect', () => {
// Disconnect event
});
以下示例演示了在Node.js中使用Process disconnect事件属性:
示例1:
文件名: 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 (process.connected) {
console.log("Child Process connected!")
console.log("Disconnecting in 3000ms")
setTimeout(() => {
process.disconnect();
}, 3000);
}
process.on('disconnect', () => {
console.log("Child Process disconnected!")
});
输出:
In child.js
Child Process connected!
Disconnecting in 3000ms
Child Process disconnected!
示例2:
文件名: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);
文件名:child2.js
console.log("In Child Process!")
process.disconnect()
process.on('disconnect', () => {
console.log(`Child process disconnected`);
});
输出:
In Child Process!
Child process disconnected
参考: https://nodejs.org/api/process.html#event-disconnect