當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。