Node.js®とは
非同期イベント駆動型のJavaScript実行環境であるNode.jsはスケール可能なネットワークアプリケーションを構築するために設計されています。次の「hello world」の例では多数のネットワーク接続を同時に処理できます。各ネットワーク接続でコールバックが呼び出されますが、実行する処理がない場合は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);
```createServer } = var require: NodeJS.Require
(id: string) => any
Used to import modules, `JSON`, and local files.require('node:http');
const const hostname: "127.0.0.1"
hostname = '127.0.0.1';
const const port: 3000
port = 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);
```createServer((req: IncomingMessage
req, 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.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.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!
```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: 3000
port, 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
```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.log(`Server running at http://${const hostname: "127.0.0.1"
hostname}:${const port: 3000
port}/`);
});
これはOSのスレッドを使用する一般的な同時実行モデルとは対照的です。スレッドベースのネットワーク処理は比較的効率が悪く、使いこなすのが非常に難しくなります。さらにNode.jsではロックがないため、プロセスのデッドロックの心配から解放されます。Node.jsにはI/Oを直接実行する関数がほとんどないため、Node.js標準ライブラリーの同期メソッドを使用してI/Oが実行される場合を除いてプロセスがブロックされることはありません。何もブロックしないNode.jsでスケーラブルなシステムを開発するのは非常に合理的です。
もしこの内容に馴染みがない場合は、さらに詳しく解説しているBlocking vs. Non-Blockingを確認してください。
Node.jsはRubyのEvent MachineやPythonのTwistedに影響を受けており、似たシステム設計になっています。Node.jsはイベントモデルをもう少し深掘りしています。Node.jsはイベントループをライブラリーとしてではなく実行環境の構成要素として提供します。他のシステムではイベントループを開始するために常にブロック処理の呼び出しがあります。一般的にはスクリプトの最初にコールバックによって振る舞いが定義され、最後に EventMachine::run()
のようなブロック処理の呼び出しによってサーバーが起動されます。Node.jsにはこのようなイベントループの開始時の呼び出しがありません。Node.jsは入力されたスクリプトを実行したあと、単にイベントループに入ります。Node.jsは実行するコールバックがなくなるとイベントループを終了します。この動作はブラウザー上のJavaScriptと同じでイベントループはユーザーから隠されています。
HTTPはNode.jsの中では第一級オブジェクトであり、ストリーミングや低レイテンシーを意識して設計されています。このためNode.jsはウェブのライブラリーやフレームワークの基盤として適しています。
Node.jsはスレッドを用いず設計されていますが、マルチコアを利用できないわけではありません。子プロセスはchild_process.fork()
APIを使って作成でき、簡単に通信できるように設計されています。これと同じインターフェイスをもとに作られたのがcluster
モジュールで、プロセス間でソケットを共有することでコアの負荷分散を行えます。
Node.js公式の情報源
Node.jsを利用する上で信頼性と安全性を確保するために、常に公式の情報源を確認してください。非公式の情報源からの電子メール、バイナリー、ダウンロード処理といったものを信用しないにしてください。
Node.js公式のドメイン
Node.jsのダウンロードと公式ドキュメントの参照は次のドメインのみを使用してください:
- nodejs.org
- nodejs.dev (https://nodejs.org にリダイレクトされます)
- iojs.org (https://nodejs.org にリダイレクトされます)
公式のnpmパッケージ
Node.jsチームは公式npmパッケージを次のスコープで管理しています:
さらにNode.jsチームはnodejs-foundation
のnpmアカウントで公開されているパッケージを管理しています。
また、他のNode.js関連パッケージ(undici
のようなもの)もプロジェクトに密接に関係する貢献者によって管理されているかもしれません。
Node.jsチームのパッケージを利用することで公式にサポートされているNode.jsコンポーネントを利用していることが保証されます。
公式GitHub Organization
Node.jsとその関連プロジェクトは次の公式GitHub Organizationで管理されています:
公式コミュニケーションチャンネル
Node.jsとOpenJS Foundationはさまざまな公式チャネルやコミュニティがサポートするチャネルを通じて連携しています。参加方法の詳細は活動への参加ページにあります。
ウェブサイトの問題とダウンタイムの報告
Node.jsのウェブサイトで問題が発生した場合はNode.jsウェブサイトリポジトリーに報告してください。障害に関するリアルタイムの情報についてはNode.js Status Page をご確認ください。