首頁  >  文章  >  web前端  >  NodeJS 簡介

NodeJS 簡介

Linda Hamilton
Linda Hamilton原創
2024-10-24 06:22:02657瀏覽

Node.js 是一個基於 Chrome 的 V8 JavaScript 引擎所建構的強大且流行的 JavaScript 執行階段。

特徵

1) 事件驅動架構:
Node.js 使用事件驅動的非阻塞 I/O 模型

阻止操作:
程式執行暫停或等待,直到操作完成。在此期間,系統或執行緒無法執行其他任務。
阻塞操作通常是同步的,因為它們會停止執行以下程式碼直到完成

同步:
程式等待操作完成,然後再轉到下一個任務。
前任。在 Node.js 中同步讀取檔:

非阻塞操作:
程式不會等待操作完成。相反,它會繼續執行其他任務,同時操作在背景繼續進行。

非同步:
程式可以在等待操作完成的同時執行其他任務。更複雜的是,需要處理非同步結果的機制(例如回呼、promise、async/await)。

事件循環
事件循環負責管理和執行非同步操作的回調。

2) 非同步與非阻塞:

事件循環是 Node.js 的核心元件,用於管理和協調非同步操作的執行。

事件循環的組成部分:

呼叫堆疊:
呼叫堆疊追蹤當前正在執行的函數。它是一個堆疊資料結構,其中函數在呼叫時添加,在完成時刪除。

回呼隊列:
此佇列保存已完成並等待執行的非同步操作(如 I/O 操作、計時器或網路請求)的回調。

事件佇列:
與回調佇列類似,它保存事件及其關聯的回調。事件是指使用者互動、計時器到期或網路回應等。

微任務隊列(或下一個 Tick 隊列):
此佇列保存微任務,這些微任務通常是 Promise 及其 .then() 回呼。微任務比回調具有更高的優先權,並且在事件佇列之前進行處理。

計時器:
事件循環使用 setTimeout() 和 setInterval() 來管理計時器。這些計劃在指定的延遲後或定期間隔執行。

I/O 操作:
事件循環處理 I/O 操作,例如檔案讀取、網路請求和資料庫查詢。它允許 Node.js 非同步處理這些操作,而不會阻塞主執行緒。

const fs = require('fs');

// Asynchronous file read
fs.readFile('file.txt', 'utf8', (err, data) => {
  console.log('File read complete:', data);
});

// Synchronous operation
console.log('This prints first');

// Timer
setTimeout(() => {
  console.log('Timeout executed');
}, 0);

console.log('This prints second');

執行順序:

同步程式碼(console.log('This prints first') 和 console.log('This prints secondary'))首先運行,因為它被加入到呼叫堆疊中。

fs.readFile回呼和setTimeout回呼被加入到各自的佇列(回呼佇列和定時器佇列)。

同步程式碼執行後,事件循環處理定時器佇列並執行setTimeout回呼。接下來,它處理回呼佇列並執行 fs.readFile 回呼。

伺服器創建

const fs = require('fs');

// Asynchronous file read
fs.readFile('file.txt', 'utf8', (err, data) => {
  console.log('File read complete:', data);
});

// Synchronous operation
console.log('This prints first');

// Timer
setTimeout(() => {
  console.log('Timeout executed');
}, 0);

console.log('This prints second');

Introduction to NodeJS

回調

回呼是作為參數傳遞到另一個函數的函數,然後在外部函數內部呼叫該函數以完成某種例程或操作。

var http = require('http');

const server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
})

server.listen(8080, () => {
  console.log('Server running at http://127.0.0.1:8080/');
});

承諾

表示非同步操作最終完成(或失敗)及其結果值的物件。

function downloadFile(url, callback) {
    console.log(`Starting to download file from ${url}`);
    setTimeout(() => {
        console.log('File downloaded successfully');
        callback('File content');
    }, 2000); 
}

function processFile(content) {
    console.log(`Processing file with content: ${content}`);
}

downloadFile('http://example.com/file', processFile);

保持聯繫!
如果您喜歡這篇文章,請不要忘記在社交媒體上關注我以獲取更多更新和見解:

推特: madhavganesan
Instagram:madhavganesan
領英: madhavganesan

以上是NodeJS 簡介的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn