如何在 Node.js 中退出一個程序?


有些時候,我們需要根據某個條件退出 Node.js 中的程序。對於這種情況,我們有以下方法可以退出或終止任何 Node.js 程序。

方法 1:使用 Ctrl+C 鍵

我希望每個人都知道這個退出任何外部 Node.js 程序的快捷方式。可以使用這個快捷方式,透過在終端敲這個命令來停止任何執行程序。

方法 2:使用 process.exit() 函式

這個函式指示 Node.js 立即結束正在執行的程序並帶有退出碼。Node.js 會強制當前正在執行的程序在遇到此語句時停止執行。

語法

process.exit(code)

這裡的 code 定義了程式碼的值,它可以是 0 或 1。“0”表示沒有錯誤地結束程序,而“1”表示由於某些錯誤而結束程序。

示例 1

// Initializing an empty array
var arr = [];
var a=2, b=8;

// Running the loop infinitely
while (a < 10 || b < 10) {
   // Incrementing the value of a&b
   a = a + 1;
   b = b + 2;

   // Pushing the sum into array
   arr.push(a + b);

   // Process will be exited when a & b becomes equal
   if (a > 2 && b>4) {
      console.log("Exiting since a>2 & b>4");
      process.exit(0);
      console.log("Process exited successfully")
   }
}

輸出

C:\home
ode>> node exit.js Exiting since a>2 & b>4

方法 3 - 使用 process.on() 函式

這個 Node.js 程序是一個全域性物件。在程式碼中到達行尾時它會自動退出該程序。我們可以使用 process.on 函式來退出 Node.js 中的任何程序。

語法

process.on()

示例 2

console.log('Welcome to TutorialsPoint !');

process.on('exit', function (code) {
   return console.log(`Process to exit with code ${code}`);
});

輸出

C:\home
ode>> node exit.js Welcome to TutorialsPoint ! Process to exit with code 0

更新於: 2022 年 1 月 17 日

10K+ 次檢視

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.