当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js Process disconnect用法及代码示例


在本文中,我们将讨论 Process 对象的断开连接事件。如果 Node.js 进程是使用 IPC 通道启动的,则当 IPC 通道关闭时,将发出断开连接事件。

用法:

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

下面的示例说明了 Node.js 中进程断开事件属性的用法:

示例 1:

文件名: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);

文件名: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!") 
});

输出:

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

示例 2:

文件名: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);

文件名:child2.js

Javascript


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



相关用法


注:本文由纯净天空筛选整理自aritrikghosh784大神的英文原创作品 Node.js Process disconnect Event。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。