關於 Node.js®

Node.js 身為非同步事件驅動的 JavaScript 執行環境,旨在建構可擴展的網路應用程式。在下面的 "hello world" 範例中,Node.js 可以同時處理多個並行連線。每個連線都會觸發回呼函式,但如果沒有任何工作需要處理, Node.js 就會進入休眠。

const { function createServer<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse>(requestListener?: RequestListener<Request, Response>): Server<Request, Response> (+1 overload)
Returns a new instance of {@link Server } . The `requestListener` is a function which is automatically added to the `'request'` event. ```js import http from 'node:http'; // Create a local server to receive data from const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ```js import http from 'node:http'; // Create a local server to receive data from const server = http.createServer(); // Listen to the request event server.on('request', (request, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ```
@sincev0.1.13
createServer
} =
var require: NodeJS.Require
(id: string) => any
Used to import modules, `JSON`, and local files.
@sincev0.1.13
require
('node:http');
const const hostname: "127.0.0.1"hostname = '127.0.0.1'; const const port: 3000port = 3000; const const server: Server<typeof IncomingMessage, typeof ServerResponse>server = createServer<typeof IncomingMessage, typeof ServerResponse>(requestListener?: RequestListener<typeof IncomingMessage, typeof ServerResponse> | undefined): Server<...> (+1 overload)
Returns a new instance of {@link Server } . The `requestListener` is a function which is automatically added to the `'request'` event. ```js import http from 'node:http'; // Create a local server to receive data from const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` ```js import http from 'node:http'; // Create a local server to receive data from const server = http.createServer(); // Listen to the request event server.on('request', (request, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ```
@sincev0.1.13
createServer
((req: IncomingMessagereq,
res: ServerResponse<IncomingMessage> & {
    req: IncomingMessage;
}
res
) => {
res: ServerResponse<IncomingMessage> & {
    req: IncomingMessage;
}
res
.ServerResponse<Request extends IncomingMessage = IncomingMessage>.statusCode: number
When using implicit headers (not calling `response.writeHead()` explicitly), this property controls the status code that will be sent to the client when the headers get flushed. ```js response.statusCode = 404; ``` After response header was sent to the client, this property indicates the status code which was sent out.
@sincev0.4.0
statusCode
= 200;
res: ServerResponse<IncomingMessage> & {
    req: IncomingMessage;
}
res
.
OutgoingMessage<IncomingMessage>.setHeader(name: string, value: number | string | readonly string[]): ServerResponse<IncomingMessage> & {
    req: IncomingMessage;
}
Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name.
@sincev0.4.0@paramname Header name@paramvalue Header value
setHeader
('Content-Type', 'text/plain');
res: ServerResponse<IncomingMessage> & {
    req: IncomingMessage;
}
res
.
Stream.Writable.end(chunk: any, cb?: () => void): ServerResponse<IncomingMessage> & {
    req: IncomingMessage;
} (+2 overloads)
Calling the `writable.end()` method signals that no more data will be written to the `Writable`. The optional `chunk` and `encoding` arguments allow one final additional chunk of data to be written immediately before closing the stream. Calling the {@link write } method after calling {@link end } will raise an error. ```js // Write 'hello, ' and then end with 'world!'. import fs from 'node:fs'; const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // Writing more now is not allowed! ```
@sincev0.9.4@paramchunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`.@paramencoding The encoding if `chunk` is a string@paramcallback Callback for when the stream is finished.
end
('Hello World');
}); const server: Server<typeof IncomingMessage, typeof ServerResponse>server.Server.listen(port?: number, hostname?: string, listeningListener?: () => void): Server<typeof IncomingMessage, typeof ServerResponse> (+8 overloads)
Start a server listening for connections. A `net.Server` can be a TCP or an `IPC` server depending on what it listens to. Possible signatures: * `server.listen(handle[, backlog][, callback])` * `server.listen(options[, callback])` * `server.listen(path[, backlog][, callback])` for `IPC` servers * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` event. All `listen()` methods can take a `backlog` parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). All {@link Socket } are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for details). The `server.listen()` method can be called again if and only if there was an error during the first `server.listen()` call or `server.close()` has been called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. One of the most common errors raised when listening is `EADDRINUSE`. This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry after a certain amount of time: ```js server.on('error', (e) => { if (e.code === 'EADDRINUSE') { console.error('Address in use, retrying...'); setTimeout(() => { server.close(); server.listen(PORT, HOST); }, 1000); } }); ```
listen
(const port: 3000port, const hostname: "127.0.0.1"hostname, () => {
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`Server running at http://${const hostname: "127.0.0.1"hostname}:${const port: 3000port}/`);
});

這與目前更常見的作業系統多執行緒並行模型形成鮮明對比。執行緒導向的網路效率相對較低且難以使用。此外,Node.js 的使用者也不必擔心死鎖 (deadlock) 問題,因為系統中並沒有上鎖機制。Node.js 中幾乎沒有直接執行 I/O 的函式,所以除了使用 Node.js 標準函式庫的同步方法進行 I/O 外,不會阻塞行程。少了阻塞使得在 Node.js 中開發可擴展的系統變得非常容易。

如果您不熟悉這些術語,可以參考這篇完整的文章〈阻塞與非阻塞概述(EN)〉


Node.js 在設計上類似於 Ruby 的 Event Machine 和 Python 的 Twisted 等系統,也受到了它們的影響並進一步發展事件模型。它將事件迴圈呈現為一個執行時期結構而非函式庫。在其他系統中,總是需要阻塞式呼叫才能啟動事件迴圈。通常,行為是定義於在指令稿開頭的回呼函式,並在結尾透過 EventMachine::run() 等阻塞式呼叫啟動伺服器。然而在 Node.js 中卻沒有這種啟動事件迴圈的呼叫。Node.js 會在執行輸入指令稿後直接進入事件迴圈。若無需要執行的回呼函式,Node.js 就會退出事件迴圈。這種行為類似於瀏覽器中的 JavaScript,即使用者不會感知事件迴圈的存在。

HTTP 是 Node.js 中的一等公民,在設計時就考慮到了串流處理和低延遲。這使得 Node.js 非常適合作為 web 函式庫或框架的基礎。

雖然 Node.js 的設計中沒有執行緒,但這並不代表其無法善用多核心環境。透過我們的 child_process.fork() API 可以產生能便利互相溝通的子行程。基於相同介面的 cluster 模組則可讓您在程序間共享 socket,以達成多核心負載平衡。

官方 Node.js 資源

為確保您使用真正且安全的 Node.js,請總是使用官方來源。不要信任來自非官方來源的信件、二進位檔、下載連結。

官方 Node.js 網域

於下載 Node.js 二進位檔或存取官方文件時,請只使用下列網域:

官方 npm 套件

Node.js 團隊維護下列的官方 npm 套件範圍:

此外,Node.js 團隊維護由 nodejs-foundation npm 帳號發布的套件,而其他 Node.js 相關的套件(如: undici)可能由與本專案關係密切的貢獻者維護。

使用來自 Node.js 團隊的套件,可確保您使用的是官方支援的 Node.js 元件。

官方 GitHub 組織

Node.js 及相關專案是由這些官方 GitHub 組織維護:

官方交流管道

Node.js 及 OpenJS 基金會會使用數種官方及社群支援的交流管道。您可以在 加入我們(EN) 頁面了解詳情。

回報網站問題及下線

如果您遇到 Node.js 網站的問題,請在Node.js 網站儲存庫回報問題。 關於網站下線狀況的即時更新,請造訪 Node.js 狀態頁面