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


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