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


Node.js process.connected用法及代碼示例


process.connected屬性是流程模塊的內置屬性,子流程使用該屬性來檢查其是否與父流程連接。

用法:

process.connected

返回值:如果該進程是從另一個進程派生的,則如果兩個進程已連接,則process.connected屬性將返回true,否則將返回false。



範例1:如果進程已連接,則process.connected將返回true。

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 it is connected
if (process.connected) {
  
    // Print messages
    console.log("Child.js is connected");
} else {
  
    // Print messages
    console.log("Child.js is disconnected");
}

使用以下命令運行Parent.js文件:

node Parent.js

輸出:

In Child.js
Child.js is connected

範例2:如果該進程已斷開連接,則process.connected將返回false。

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')
  
// Disconnect the process
process.disconnect();
  
// If it is connected
if (process.connected) {
  
    // Print messages
    console.log("Child.js is connected");
} else {
  
    // Print messages
    console.log("Child.js is disconnected");
}

使用以下命令運行Parent.js文件:

node Parent.js

輸出:

In Child.js
Child.js is disconnected

參考: https://nodejs.org/api/process.html#process_process_connected


注:本文由純淨天空篩選整理自GeeksforGeeks大神的英文原創作品 Node.js process.connected Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。