Node.js API (nodejs.org)
Node.js API ドキュメントの中から、モデルが間違いやすい点(安全でないデフォルト、落とし穴、非推奨)を凝縮しています。各主張の末尾に nodejs.org のページへのリンクがあります。
対象バージョン
読み込んだドキュメントは v26.13.0 です。多くのプロジェクトは v24 LTS 系で動作しているため、新しい機能については「v25.x で追加」や「v26.x で追加」と記載し、バックポートバージョンが明記されていない限り v24 では利用できないことを示します。 https://nodejs.org/docs/latest/api/
フラグ付きの機能に依存する前に、process.version または機能検出(process.features.typescript、process.features.require_module)を確認してください。 https://nodejs.org/docs/latest/api/process.html
以下のルールを読み、対応するリファレンスファイルを開いてください。
最重要ルール
- ファイルを開く前に
access()、exists()、stat()を呼び出さないでください。直接開いてENOENT/EEXISTを処理してください(排他的作成にはフラグ'wx'を使用)。 https://nodejs.org/docs/latest/api/fs.html#fsaccesspath-mode-callback - すべての
FileHandleは明示的にクローズしてください。理想的にはawait usingを使用します。GC に任せたFileHandleはエラーをスローします。 https://nodejs.org/docs/latest/api/deprecations.html#DEP0137 - ストリームの合成には
pipeline()を使用し、.pipe()チェーンは使わないでください。write()がfalseを返した場合に適切にバックプレッシャーを処理してください。 https://nodejs.org/docs/latest/api/stream.html#readablepipedestination-options - すべてのイベントエミッター、ストリーム、ソケット、リクエスト、子プロセスに
'error'リスナーを追加してください。ハンドルされない'error'はプロセスをクラッシュさせます。 https://nodejs.org/docs/latest/api/events.html#error-events - エラー判別は
err.codeで行い、err.messageは使わないでください。 https://nodejs.org/docs/latest/api/errors.html#errorcode process.exit()の代わりにprocess.exitCodeを設定してください。process.exit()は標準出力を切り詰める可能性があります。 https://nodejs.org/docs/latest/api/process.html#processexitcode'uncaughtException'発生後は処理を再開せず、同期的に後片付けを行い終了してください。 https://nodejs.org/docs/latest/api/process.html#warning-using-uncaughtexception-correctly- レガシーな
process.nextTick()よりもqueueMicrotask()を優先してください。 https://nodejs.org/docs/latest/api/process.html#when-to-use-queuemicrotask-vs-processnexttick execFile()/spawn()はシェルなしで使用してください。shell: trueで引数を渡してもエスケープされません。 https://nodejs.org/docs/latest/api/deprecations.html#DEP0190- すべての HTTP クライアントレスポンスボディを消費し(最低でも
res.resume())、req.on('error')をアタッチし、timeoutがリクエストを中断しないことを覚えておいてください。中断するにはdestroy()を呼び出します。 https://nodejs.org/docs/latest/api/http.html#class-httpclientrequest - リバースプロキシがないサーバーでは、
headersTimeoutをゼロ以外に設定してください。 https://nodejs.org/docs/latest/api/http.html#serverheaderstimeout - WHATWG
URLを使用してください。url.parse()は非推奨であり、これに対して CVE は発行されません。 https://nodejs.org/docs/latest/api/deprecations.html#DEP0169 path.isAbsolute()はパス・トラバーサルを防ぎません。path.normalize()は字句的な処理であり、システムのパス解決方法を変える可能性があります。絶対パスに解決した後、結果がルートディレクトリ内に収まっていることを確認してください。 https://nodejs.org/docs/latest/api/path.html#pathisabsolutepath- デフォルトでは
Buffer.alloc()を使用し、ビューにはBuffer.subarray()を使用し、new Buffer()は絶対に使わないでください。 https://nodejs.org/docs/latest/api/deprecations.html#DEP0005 - 機密情報の比較は、同じ長さのバッファで
crypto.timingSafeEqual()を使用してください。 https://nodejs.org/docs/latest/api/crypto.html#cryptotimingsafeequala-b - zlib で信頼できないデータを展開する場合は、
maxOutputLengthを設定してください(デフォルトはbuffer.kMaxLength)。 https://nodejs.org/docs/latest/api/zlib.html#class-options package.jsonに"type"を設定し、"exports"の条件では"default"を最後に配置してください。 https://nodejs.org/docs/latest/api/packages.html#determining-module-system- ESM の
require()は同期グラフに対して機能します。グラフ内のどこかでトップレベル await があると、ERR_REQUIRE_ASYNC_MODULEがスローされます。 https://nodejs.org/docs/latest/api/modules.html#loading-ecmascript-modules-using-require - 型除去は
.tsファイルを型チェックなしで実行します。enum、明示的な.ts拡張子、import type、tsconfigのpathsは使用できません。これは v25.2.0 以降で安定しています(v24.12.0 にバックポート)。process.features.typescriptで検出できます。 https://nodejs.org/docs/latest/api/typescript.html#typescript-features , https://nodejs.org/docs/latest/api/typescript.html#type-stripping - モジュールフックは
module.registerHooks()で登録してください。module.register()は v26 で非推奨になりました。 https://nodejs.org/docs/latest/api/deprecations.html#DEP0205 async_hooks.createHook()よりもAsyncLocalStorageを優先してください。 https://nodejs.org/docs/latest/api/async_hooks.htmlnode:testのサブテストにはawait t.test()を使用してください。 https://nodejs.org/docs/latest/api/test.html#subtestsnode:vmと WASI はサンドボックスではありません。Permission Model も信頼できないコードを安全に実行する方法ではありません。これらの目的で使用しないでください。 https://nodejs.org/docs/latest/api/permissions.html#process-based-permissions- サーバー、ストリーム、子プロセスは
AbortSignalではなく、using/await usingで破棄してください。シグナルはキャンセルとタイムアウトのために残してください。 https://nodejs.org/docs/latest/api/deprecations.html#DEP0209 dns.lookup()はスレッドプール上のgetaddrinfoであり、DNS クエリではありません。 https://nodejs.org/docs/latest/api/dns.html#implementation-considerations- プールのサイズ設定には
os.availableParallelism()を使用してください。 https://nodejs.org/docs/latest/api/os.html#osavailableparallelism node:sqlite:パラメータはバインドし、SQL に直接埋め込まないでください。 https://nodejs.org/docs/latest/api/sqlite.html#binding-parameters- CI では
--pending-deprecationを指定して実行し、非推奨を表面化させてください。 https://nodejs.org/docs/latest/api/deprecations.html
リファレンスファイル
| ファイル | 参照する目的 |
|---|---|
| references/fs.md | TOCTOU、FileHandle、readFile/writeFile、rm、glob、fs.watch |
| references/path-and-url.md | path、トラバーサル、file: URL、WHATWG URL、querystring |
| references/crypto.md | KeyObject、timingSafeEqual、ハッシュ、pbkdf2、scrypt、脆弱なアルゴリズム |
| references/ciphers-and-webcrypto.md | AEAD タグ、GCM、鍵ラップ、subtle、鍵形式 |
| references/streams.md | pipeline、バックプレッシャー、highWaterMark、finished、ストリームの実装 |
| references/web-streams-and-stream-iter.md | Web Streams、node:stream/iter |
| references/buffer.md | alloc と allocUnsafe の違い、エンコーディング、Blob |
| references/zlib.md | 展開爆弾、フラッシュ、Zstd |
| references/http-client.md | http.request、エージェント、キープアライブ、プロキシ |
| references/http-server.md | タイムアウト、グレースフルシャットダウン、HTTPS サーバー |
| references/net-dns-dgram.md | TCP、BlockList、dns.lookup と resolve の違い、UDP |
| references/tls.md | SNI、暗号スイート、CA ストア、セッション再開 |
| references/http2.md | セキュアサーバー、allowHTTP1、強化 |
| references/process.md | 終了コード、シグナル、uncaughtException、拒否 |
| references/cli-and-env-files.md | NODE_OPTIONS、--env-file、--watch |
| references/permissions.md | --permission、既知のギャップ |
| references/errors.md | error.code、cause、エラーコード |
| references/events-and-timers.md | captureRejections、events.once、EventTarget、タイマー |
| references/async-context-and-diagnostics-channel.md | AsyncLocalStorage、diagnostics_channel |
| references/util-and-console.md | util、Console |
| references/os-tty-readline-repl.md | os、tty、readline、REPL |
| references/test-runner.md | サブテスト、分離、カバレッジ、レポーター、モック |
| references/assert-and-bench.md | node:assert/strict、深い等価性、node:bench |
| references/esm-and-commonjs.md | "type"、JSON インポート、import.meta、require(esm) |
| references/packages.md | "exports"、"imports"、条件、デュアルパッケージ |
| references/typescript-and-module-hooks.md | 型除去、registerHooks、findPackageJSON |
| references/globals.md | fetch、AbortSignal、グローバル |
| references/child-process.md | execFile と exec の違い、maxBuffer、IPC |
| references/worker-threads-and-cluster.md | プール、転送リスト、クラスター |
| references/vm-wasi-vfs.md | vm、WASI、node:vfs |
| references/performance-and-profiling.md | perf_hooks、ヒープスナップショット |
| references/debugging-and-reports.md | インスペクター、診断レポート |
| references/sqlite.md | Database、デフォルト、バインド、型変換 |
| references/sea-and-native.md | SEA、Node-API ルール、node:ffi |
| references/deprecations.md | DEP コード、削除された API、codemod |
参照したページ、バージョン、取得日は SOURCES.md に一覧されています。