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


Node.js process.disconnect()用法及代码示例


process.disconnect()属性是进程模块的内置应用程序编程接口,子进程使用该接口与父进程断开连接。此方法不适用于根进程,因为它没有任何父进程。

用法:

process.disconnect()

参数:它不带任何参数。

返回值:它没有返回值。



范例1:在Parent.js中,我们产生子进程。在Child.js中,我们收到消息在Child.js中。然后,如果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 the send method is available
if (process.connected) {
  
    // Check if its connected or not
    if (process.connected == true) {
        console.log("Child.js is connected.");
    }
  
    // Use process.disconnect() to disconnect
    process.disconnect();
  
    // Check if its connected or not
    if (process.connected == false) {
        console.log("Child.js has been disconnected.");
    }
}

使用以下命令运行Parent.js:

node Parent.js

输出:

In Child.js
Child.js is connected.
Child.js has been 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 = 'Child.js';
  
// Spawn child process
const child = fork(child_file);

Child.js


console.log('In Child.js')
  
// If the send method is available
if (process.connected) {
  
    // Send multiple messages
    setTimeout((function () {
        if (process.connected == true) {
            console.log("This was sent after 1 second.");
        }
    }), 1000);
  
    setTimeout((function () {
        if (process.connected == true) {
            console.log("This was sent after 2 seconds.");
        }
    }), 2000);
  
    // Disconnect after 2.5 seconds
    setTimeout((function () {
        process.disconnect();
    }), 2500);
  
    setTimeout((function () {
        if (process.connected == true) {
            console.log("This was sent after 3 seconds.");
        }
    }), 3000);
}

使用以下命令运行Parent.js:

node Parent.js

输出:

In Child.js
Message from child:This was sent after 1 second.
Message from child:This was sent after 2 seconds.

参考: https://nodejs.org/api/process.html#process_process_disconnect

相关用法


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