Node.js v21.7.2 ドキュメント
- Node.js v21.7.2
- ► 目次
-
► インデックス
- アサーションテスト
- 非同期コンテキストトラッキング
- 非同期フック
- バッファ
- C++ アドオン
- Node-API を使用した C/C++ アドオン
- C++ エンベダー API
- 子プロセス
- クラスタ
- コマンドラインオプション
- コンソール
- Corepack
- 暗号化
- デバッガ
- 非推奨 API
- 診断チャネル
- DNS
- ドメイン
- エラー
- イベント
- ファイルシステム
- グローバルオブジェクト
- HTTP
- HTTP/2
- HTTPS
- インスペクタ
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール: `node:module` API
- モジュール: パッケージ
- ネットワーク
- OS
- パス
- パフォーマンスフック
- パーミッション
- プロセス
- Punnycode
- クエリ文字列
- Readline
- REPL
- レポート
- 単一実行可能アプリケーション
- ストリーム
- 文字列デコーダ
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/データグラム
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- ワーカースレッド
- Zlib
- ► その他のバージョン
- ► オプション
ドメイン#
ソースコード: lib/domain.js
このモジュールは非推奨になる予定です。 代替 API が確定次第、このモジュールは完全に非推奨になります。ほとんどの開発者は、このモジュールを使用する必要はありません。ドメインが提供する機能を絶対に必要とするユーザーは、当面は使用できますが、将来、別のソリューションに移行する必要があることを想定する必要があります。
ドメインは、複数の異なる IO 操作を単一のグループとして処理する方法を提供します。ドメインに登録されたイベントエミッタまたはコールバックのいずれかが 'error'
イベントを発行するか、エラーをスローすると、process.on('uncaughtException')
ハンドラでエラーのコンテキストを失うことなく、またはエラーコードでプログラムがすぐに終了することなく、ドメインオブジェクトに通知されます。
警告: エラーを無視しないでください!#
ドメインエラーハンドラは、エラーが発生したときにプロセスをシャットダウンする代わりにはなりません。
JavaScript の throw
の動作の性質上、参照のリークやその他の未定義の脆弱な状態の作成なしに、「中断したところから安全に再開する」方法はほとんどありません。
スローされたエラーに対応する最も安全な方法は、プロセスをシャットダウンすることです。もちろん、通常の Web サーバーでは、多くのオープン接続がある場合があり、エラーが他のユーザーによってトリガーされたためにそれらを突然シャットダウンするのは妥当ではありません。
より良いアプローチは、エラーをトリガーしたリクエストにエラー応答を送信し、他のリクエストを通常の時間で終了させ、そのワーカーで新しいリクエストのリスニングを停止することです。
このように、domain
の使用はクラスタモジュールと連携して機能します。プライマリプロセスは、ワーカーでエラーが発生したときに新しいワーカーをフォークできます。複数のマシンにスケールする Node.js プログラムの場合、終了するプロキシまたはサービスレジストリは障害を認識し、それに応じて反応できます。
たとえば、これは良い考えではありません。
// XXX WARNING! BAD IDEA!
const d = require('node:domain').create();
d.on('error', (er) => {
// The error won't crash the process, but what it does is worse!
// Though we've prevented abrupt process restarting, we are leaking
// a lot of resources if this ever happens.
// This is no better than process.on('uncaughtException')!
console.log(`error, but oh well ${er.message}`);
});
d.run(() => {
require('node:http').createServer((req, res) => {
handleRequest(req, res);
}).listen(PORT);
});
ドメインのコンテキストと、プログラムを複数のワーカープロセスに分離する回復力を使用することで、より適切に反応し、はるかに安全にエラーを処理できます。
// Much better!
const cluster = require('node:cluster');
const PORT = +process.env.PORT || 1337;
if (cluster.isPrimary) {
// A more realistic scenario would have more than 2 workers,
// and perhaps not put the primary and worker in the same file.
//
// It is also possible to get a bit fancier about logging, and
// implement whatever custom logic is needed to prevent DoS
// attacks and other bad behavior.
//
// See the options in the cluster documentation.
//
// The important thing is that the primary does very little,
// increasing our resilience to unexpected errors.
cluster.fork();
cluster.fork();
cluster.on('disconnect', (worker) => {
console.error('disconnect!');
cluster.fork();
});
} else {
// the worker
//
// This is where we put our bugs!
const domain = require('node:domain');
// See the cluster documentation for more details about using
// worker processes to serve requests. How it works, caveats, etc.
const server = require('node:http').createServer((req, res) => {
const d = domain.create();
d.on('error', (er) => {
console.error(`error ${er.stack}`);
// We're in dangerous territory!
// By definition, something unexpected occurred,
// which we probably didn't want.
// Anything can happen now! Be very careful!
try {
// Make sure we close down within 30 seconds
const killtimer = setTimeout(() => {
process.exit(1);
}, 30000);
// But don't keep the process open just for that!
killtimer.unref();
// Stop taking new requests.
server.close();
// Let the primary know we're dead. This will trigger a
// 'disconnect' in the cluster primary, and then it will fork
// a new worker.
cluster.worker.disconnect();
// Try to send an error to the request that triggered the problem
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Oops, there was a problem!\n');
} catch (er2) {
// Oh well, not much we can do at this point.
console.error(`Error sending 500! ${er2.stack}`);
}
});
// Because req and res were created before this domain existed,
// we need to explicitly add them.
// See the explanation of implicit vs explicit binding below.
d.add(req);
d.add(res);
// Now run the handler function in the domain.
d.run(() => {
handleRequest(req, res);
});
});
server.listen(PORT);
}
// This part is not important. Just an example routing thing.
// Put fancy application logic here.
function handleRequest(req, res) {
switch (req.url) {
case '/error':
// We do some async stuff, and then...
setTimeout(() => {
// Whoops!
flerb.bark();
}, timeout);
break;
default:
res.end('ok');
}
}
Error
オブジェクトへの追加#
Error
オブジェクトがドメインを通過するたびに、いくつかの追加フィールドが追加されます。
error.domain
エラーを最初に処理したドメイン。error.domainEmitter
エラーオブジェクトで'error'
イベントを発行したイベントエミッタ。error.domainBound
ドメインにバインドされ、エラーを最初の引数として渡されたコールバック関数。error.domainThrown
エラーがスローされたか、発行されたか、バインドされたコールバック関数に渡されたかを示すブール値。
暗黙的バインディング#
ドメインが使用されている場合、すべての新しい EventEmitter
オブジェクト(ストリームオブジェクト、リクエスト、レスポンスなど)は、作成時のアクティブなドメインに暗黙的にバインドされます。
さらに、低レベルのイベントループリクエスト(fs.open()
やその他のコールバックを受け取るメソッドなど)に渡されるコールバックは、アクティブなドメインに自動的にバインドされます。それらがエラーをスローした場合、ドメインはそのエラーをキャッチします。
過剰なメモリ使用を回避するために、Domain
オブジェクト自体は、アクティブなドメインの子として暗黙的に追加されません。もしそうであれば、リクエストとレスポンスオブジェクトが適切にガベージコレクションされるのを簡単に妨げることができてしまいます。
Domain
オブジェクトを親 Domain
の子としてネストするには、明示的に追加する必要があります。
暗黙的なバインディングは、スローされたエラーと 'error'
イベントを Domain
の 'error'
イベントにルーティングしますが、EventEmitter
を Domain
に登録しません。暗黙的なバインディングは、スローされたエラーと 'error'
イベントのみを処理します。
明示的バインディング#
場合によっては、使用中のドメインが、特定のイベントエミッタに使用するべきドメインではない場合があります。または、イベントエミッタは 1 つのドメインのコンテキストで作成された可能性がありますが、代わりに別のドメインにバインドする必要があります。
たとえば、HTTP サーバーで使用されるドメインが 1 つある場合がありますが、各リクエストに使用する別のドメインを使用したい場合があります。
明示的なバインディングを使用すると可能です。
// Create a top-level domain for the server
const domain = require('node:domain');
const http = require('node:http');
const serverDomain = domain.create();
serverDomain.run(() => {
// Server is created in the scope of serverDomain
http.createServer((req, res) => {
// Req and res are also created in the scope of serverDomain
// however, we'd prefer to have a separate domain for each request.
// create it first thing, and add req and res to it.
const reqd = domain.create();
reqd.add(req);
reqd.add(res);
reqd.on('error', (er) => {
console.error('Error', er, req.url);
try {
res.writeHead(500);
res.end('Error occurred, sorry.');
} catch (er2) {
console.error('Error sending 500', er2, req.url);
}
});
}).listen(1337);
});
domain.create()
#
- 戻り値: <Domain>
クラス: Domain
#
- 継承元: <EventEmitter>
Domain
クラスは、エラーとキャッチされない例外をアクティブな Domain
オブジェクトにルーティングする機能をカプセル化します。
キャッチしたエラーを処理するには、その 'error'
イベントをリッスンします。
domain.members
#
ドメインに明示的に追加されたタイマーとイベントエミッタの配列。
domain.add(emitter)
#
emitter
<EventEmitter> | <Timer> ドメインに追加するエミッタまたはタイマー
エミッタをドメインに明示的に追加します。エミッタによって呼び出されたイベントハンドラのいずれかがエラーをスローした場合、またはエミッタが 'error'
イベントを発行した場合、暗黙的なバインディングと同様に、ドメインの 'error'
イベントにルーティングされます。
これは、setInterval()
と setTimeout()
から返されるタイマーにも機能します。それらのコールバック関数がエラーをスローした場合、ドメインの 'error'
ハンドラによってキャッチされます。
タイマーまたは EventEmitter
が既にドメインにバインドされていた場合、そのドメインから削除され、代わりにこのドメインにバインドされます。
domain.bind(callback)
#
callback
<Function> コールバック関数- 戻り値: <Function> バインドされた関数
返される関数は、提供されたコールバック関数のラッパーになります。返された関数が呼び出されると、スローされるエラーはドメインの 'error'
イベントにルーティングされます。
const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.bind((er, data) => {
// If this throws, it will also be passed to the domain.
return cb(er, data ? JSON.parse(data) : null);
}));
}
d.on('error', (er) => {
// An error occurred somewhere. If we throw it now, it will crash the program
// with the normal line number and stack message.
});
domain.enter()
#
enter()
メソッドは、run()
、bind()
、intercept()
メソッドで使用される配管で、アクティブなドメインを設定します。これは、domain.active
と process.domain
をドメインに設定し、ドメインモジュールによって管理されるドメインスタックにドメインを暗黙的にプッシュします(ドメインスタックの詳細については、domain.exit()
を参照してください)。enter()
の呼び出しは、ドメインにバインドされた非同期呼び出しと I/O 操作のチェーンの開始を区切ります。
enter()
を呼び出すと、アクティブなドメインのみが変更され、ドメイン自体は変更されません。enter()
と exit()
は、単一のドメインに対して任意の回数呼び出すことができます。
domain.exit()
#
exit()
メソッドは現在のドメインを終了し、ドメインスタックからポップします。実行が別の非同期呼び出しチェーンのコンテキストに切り替わるたびに、現在のドメインが終了していることを確認することが重要です。exit()
の呼び出しは、ドメインにバインドされた非同期呼び出しと I/O 操作のチェーンの終了または中断を区切ります。
現在の実行コンテキストに複数のネストされたドメインがバインドされている場合、exit()
はこのドメイン内にネストされたドメインを終了します。
exit()
を呼び出しても、アクティブなドメインのみが変更され、ドメイン自体に変更はありません。enter()
と exit()
は、単一のドメインに対して任意の回数呼び出すことができます。
domain.intercept(callback)
#
callback
<Function> コールバック関数- 戻り値: <Function> インターセプトされた関数
このメソッドは、domain.bind(callback)
とほぼ同一です。ただし、スローされたエラーをキャッチすることに加えて、関数の最初の引数として送信されたError
オブジェクトもインターセプトします。
このように、一般的なif (err) return callback(err);
パターンを、単一箇所の単一のエラーハンドラーに置き換えることができます。
const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.intercept((data) => {
// Note, the first argument is never passed to the
// callback since it is assumed to be the 'Error' argument
// and thus intercepted by the domain.
// If this throws, it will also be passed to the domain
// so the error-handling logic can be moved to the 'error'
// event on the domain instead of being repeated throughout
// the program.
return cb(null, JSON.parse(data));
}));
}
d.on('error', (er) => {
// An error occurred somewhere. If we throw it now, it will crash the program
// with the normal line number and stack message.
});
domain.remove(emitter)
#
emitter
<EventEmitter> | <Timer> ドメインから削除する emitter またはタイマー
domain.add(emitter)
と反対の動作です。指定された emitter からドメインの処理を削除します。
domain.run(fn[, ...args])
#
fn
<Function>...args
<any>
指定された関数をドメインのコンテキスト内で実行し、そのコンテキストで作成されるすべてのイベント emitter、タイマー、および低レベルのリクエストを暗黙的にバインドします。オプションで、関数は引数を受け取ることができます。
これは、ドメインを使用する最も基本的な方法です。
const domain = require('node:domain');
const fs = require('node:fs');
const d = domain.create();
d.on('error', (er) => {
console.error('Caught error!', er);
});
d.run(() => {
process.nextTick(() => {
setTimeout(() => { // Simulating some various async stuff
fs.open('non-existent file', 'r', (er, fd) => {
if (er) throw er;
// proceed...
});
}, 100);
});
});
この例では、プログラムがクラッシュする代わりに、d.on('error')
ハンドラーがトリガーされます。
ドメインとPromise#
Node.js 8.0.0 以降、Promise のハンドラーは、.then()
または .catch()
自体が呼び出されたドメイン内で実行されます。
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then((v) => {
// running in d2
});
});
コールバックは、domain.bind(callback)
を使用して特定のドメインにバインドできます。
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then(p.domain.bind((v) => {
// running in d1
}));
});
ドメインは、Promise のエラー処理メカニズムを妨げません。つまり、未処理の Promise
の拒否に対しては、'error'
イベントは発生しません。