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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。