理解 Node.js 中的節點生命週期和事件迴圈


Node.js 中的簡單 http 伺服器將註冊一個事件迴圈,該迴圈將持續監聽 http 請求。

包含伺服器建立程式碼的檔案的執行過程如下所示:

node App.js => 開始執行指令碼 => 程式碼解析,註冊事件和函式 => 事件迴圈 => 只要註冊了事件,就一直執行。

這是 Node.js 的單執行緒事件驅動方法。訪問和更新資料庫中的值也使用事件驅動方法。即使它是單執行緒的,由於其處理速度快,它也可以同時處理多個請求。

示例:

const server = http.createServer( (req, res)=>{ console.log(‘hello’); } );

在上面的示例程式碼中,createServer 方法將請求監聽器作為引數,這是一個事件。此事件將持續監聽指定埠上的 http 請求。

如何退出事件迴圈

process.exit() 是停止事件迴圈的函式。

App.js

const http = require(‘http’);
const server = http.createServer( (req, res)=>{ console.log(‘hello’); process.exit(); } );
server.listen(3000);

現在,一旦我們使用終端中的 **node App.js** 執行 App.js 檔案,事件迴圈就會開始。事件迴圈將在收到第一個 http 請求時停止。這可以透過開啟瀏覽器並導航到 localhost:3000 進行檢查,並在終端中檢視控制檯日誌。它將列印 hello 訊息並停止事件迴圈。

process.exit() 很少使用,因為我們總是希望事件迴圈保持執行以監聽 http 請求或資料庫連線。它只能根據特定需求使用。

如果我們只需要透過停止節點程序來退出終端,我們可以在終端中使用 ctrl + c 來停止節點程序。

事件迴圈遵循 **非阻塞** 程式碼執行。

簡單的事件發射器示例

// import the core module events from node.js
const events = require('events');
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
//Subscribe for FirstEvent
em.on('TutorialsPointEvent', function (data) {
   console.log(' Hello Tutorials point Event': ' + data);
});
// Raising FirstEvent
em.emit(' TutorialsPointEvent', 'This is my first Simple Node.js event emitter example on TutorialsPoint.');

更新於: 2020年5月13日

1K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.