Skip to content

Node.js チートシート

サーバーサイド開発のための、Chrome の V8 エンジン上に構築された JavaScript ランタイム。

01

はじめに

REPL とスクリプトの実行

Node.js のコードで実験するための対話シェルが、REPL(Read-Eval-Print Loop)です。開発中の自動再起動には node --watch を使いましょう。ES モジュールには、package.json の type:module か .mjs 拡張子が必要です。

nodejs
# start the REPL (interactive shell)
node

# run a script
node app.js

# run with ES modules (type: module in package.json)
node --input-type=module app.js

# execute inline code
node -e "console.log(process.version)"

# watch mode (auto-restart on change)
node --watch app.js

バージョンとランタイムフラグ

ランタイムのバージョンを表示するのが、node --version です。ランタイムの警告のスタックトレースを示すのが、--trace-warnings です。CLI フラグを保持する単一の env 変数が NODE_OPTIONS で、コンテナや npm スクリプトの中で便利です。Chrome DevTools のデバッガを開くのが、--inspect です。

nodejs
# check version
node --version    # v20.11.0
node -p "process.versions.v8"

# enable warning stack traces
node --trace-warnings app.js

# pass NODE_OPTIONS (max ~128KB string)
NODE_OPTIONS="--max-old-space-size=4096" node app.js

# inspect memory usage at runtime
node --inspect app.js

package.json とプロジェクトの初期化

package.json を作るのが、npm init です。デフォルトのモジュールシステムを決めるのが、"type" フィールドです:.js ファイルで ES モジュール構文を有効化するのが "module"、require/module.exports を保つのが "commonjs"(デフォルト)です。パッケージが require されたときのエントリポイントが、"main" です。

nodejs
# scaffold a project (answer prompts)
npm init

# non-interactive defaults
npm init -y

# "type" controls module system
# "commonjs" (default) -> require/module.exports
# "module"              -> import/export
{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": { "start": "node index.js" }
}

CommonJS 対 ES Modules

Node が 2 つのモジュールシステムをサポートします。同期であり歴史的なデフォルトが、CommonJS(require/module.exports)です。モダンな標準が、ES Modules(import/export)です。.js ファイルに対し、どのパーサが使われるか決めるのが、拡張子(.mjs/.cjs)か package.json の "type" フィールドです。

nodejs
# CommonJS (.cjs or type:commonjs) ----
const fs = require('fs');                 // import
module.exports = { greet: () => 'hi' };   // export

# ES Modules (.mjs or type:module) -------
import fs from 'fs';                      // import
export function greet() { return 'hi'; }  // named export
export default { greet };                 // default export

# .mjs is always ESM, .cjs is always CJS
node file.mjs   # forced ESM
node file.cjs   # forced CJS

グローバルオブジェクト

Node が、import なしで process、console、Buffer、タイマーのようなグローバルを提供します。CommonJS 専用なのが、__dirname と __filename です — ES モジュールでは、代わりに import.meta.url を使いましょう。ルートスコープのオブジェクトが、global です(ブラウザの window のように)。

nodejs
# available everywhere, no import needed
global;        // global namespace object
process;       // env, argv, stdin/stdout
console;       // log, error, warn, table
setTimeout;    // schedule a callback
setInterval;   // schedule repeating callback
Buffer;        // binary data (Uint8Array)
queueMicrotask;// schedule microtask
structuredClone; // deep clone

# CommonJS-only globals (not in ESM)
__dirname;     // current directory
__filename;    // current file path

実行可能なスクリプト(Shebang)

Unix 上でファイルをスタンドアロンのコマンドとして実行させるのが、shebang 行(#!/usr/bin/env node)です。chmod +x の後、./cli.js を直接実行します。コマンド名をスクリプトへマッピングするのが、package.json の "bin" フィールドで、npm へ公開される CLI ツールが使い、グローバルインストールでコマンドが公開されます。

nodejs
#!/usr/bin/env node
// cli.js - make a file directly runnable
const name = process.argv[2] || 'world';
console.log(`Hello, ${name}!`);

# make it executable (Unix) and run directly
chmod +x cli.js
./cli.js Alice        # Hello, Alice!

# or wire it up in package.json
{
  "bin": { "mycli": "./cli.js" }
}
02

モジュールシステム

CommonJS の require と exports

CommonJS のモジュールを同期的にロードし、その module.exports を返すのが、require() です。require が解決するのは、相対パス(./、../)、組み込み(fs)、node_modules です。エクスポート全体を置き換えるときは、exports ではなく module.exports へ必ず代入しましょう — exports は当初、module.exports の別名にすぎないためです。

nodejs
// math.js
function add(a, b) { return a + b; }
const PI = 3.14;

// export via module.exports
module.exports = { add, PI };
// or: exports.add = add; exports.PI = PI;

// app.js
const math = require('./math');      // .js optional
console.log(math.add(1, 2));          // 3
console.log(math.PI);                 // 3.14

// destructuring
const { add } = require('./math');
console.log(add(5, 7));               // 12

ES Modules の import/export

静的な import/export を使うのが、ES Modules です — 束縛がライブで、巻き上げられます。任意の名前でインポートされるのが、デフォルトエクスポートです(波括弧なし)。一致する名前の波括弧を必要とするのが、名前付きエクスポートです。名前空間オブジェクトを作るのが、import * as です。設計上非同期でありモダンな標準が、ESM です。

nodejs
// math.mjs (or type:module)
export function add(a, b) { return a + b; }
export const PI = 3.14;
export default function square(x) { return x * x; }

// app.mjs
import square, { add, PI } from './math.mjs';
console.log(add(1, 2));     // 3
console.log(square(5));     // 25

// import all as namespace
import * as math from './math.mjs';
console.log(math.PI);       // 3.14

動的な import()

CJS と ESM の両方で使える、動的で非同期な import が、import() です。モジュールの名前空間へ解決される Promise を返し、遅延ローディングと条件付きインポートを可能にします — 起動時間の削減や省略可能な機能のロードに最適です。サーバーでのコード分割にも使いましょう。

nodejs
// dynamic import returns a Promise
async function loadPlugin(name) {
  const mod = await import(`./plugins/${name}.mjs`);
  return mod.default;
}

// lazy-load heavy modules on demand
if (needPdf) {
  const { exportPdf } = await import('./pdf.mjs');
  exportPdf(data);
}

// works in both CommonJS and ESM
import('./optional.mjs')
  .then(mod => mod.run())
  .catch(err => console.error('load failed', err));

組み込みモジュール

Node が、npm install なしで、数十の組み込みモジュールを ship します。ほとんどがコールバック API を公開し、多くが「module/promises」のパスの下で promise 版も提供します(fs/promises、dns/promises、stream/promises)。組み込みが先に解決され、その後 node_modules が来るのが、require('module')(./ なし)です。

nodejs
// core modules - no install, just require/import
const fs = require('fs');            // file system
const path = require('path');        // path handling
const http = require('http');        // HTTP server/client
const os = require('os');            // OS info
const crypto = require('crypto');    // hashing/encryption
const { EventEmitter } = require('events');
const { Buffer } = require('buffer');
const stream = require('stream');    // streams
const net = require('net');          // TCP
const child_process = require('child_process');

// some are promise-based (Node 10+)
const fsp = require('fs/promises');  // async/await fs

モジュールのキャッシュと循環依存

解決されたパスによりモジュールをキャッシュするのが、require() です。そのため、同じモジュールのコードが 1 回動き、エクスポートが再利用されます。循環依存は機能しますが、先にロードされたモジュールが、2 番目の不完全な(部分的な)exports オブジェクトを見るため — 周りを設計しましょう。開発中のホットリロードには、require.cache の delete を。

nodejs
// modules are cached after first load
// a.js
require('./b');                 // b loads, sets module.exports
const b = require('./b');       // returns cached b (same object)
console.log(b === require('./b')); // true

// circular dependency: a -> b -> a
// a.js: const b = require('./b'); b.f();
// b.js: const a = require('./a'); // a is PARTIAL here!
//       module.exports = { f: () => a.x };

// inspect the cache
console.log(require.cache);     // map of loaded modules
delete require.cache[require.resolve('./b')]; // force reload

__dirname と import.meta.url

現在のフォルダ/ファイルのパスを与える CommonJS 専用のグローバルが、__dirname と __filename です。そのようなグローバルがないのが、ES Modules で — fileURLToPath 経由で import.meta.url から導出しましょう。現在のモジュールの file:// URL であり、__filename の ESM の代替が、import.meta.url です。

nodejs
// CommonJS - synchronous path globals
console.log(__dirname);   // /app/src
console.log(__filename);  // /app/src/index.js

// ES Modules - no __dirname, use import.meta
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const dataPath = join(__dirname, 'data.json');

// import.meta also carries the module URL
console.log(import.meta.url);  // file:///app/src/index.mjs
03

npm と pnpm

npm init と package.json

package.json をスキャフォールドするのが、npm init です。デフォルト付きでプロンプトをスキップするのが、-y です。今後の init のために ~/.npmrc へ設定を保存するのが、npm set です。組織やレジストリでの名前衝突の回避に有用なのが、スコープ付きパッケージ(@org/name)です。

nodejs
# create package.json interactively
npm init

# accept all defaults
npm init -y

# pnpm equivalent
pnpm init

# set author/license globally
npm set init-author-name "Alice"
npm set init-license MIT

# scope packages with @username
npm init --scope=@myorg

依存のインストール

列挙されたすべての依存をインストールするのが、引数なしの npm install です。名前付きなら package.json へ加わります。devDependencies(テスト/ビルドのツール、ship されない)へ入れるのが、--save-dev です。minor+patch の更新を許すのが ^ で、patch だけを許すのが ~ です。CLI ツールをグローバルにインストールするのが、-g です。

nodejs
# install everything in package.json
npm install            # alias: npm i
pnpm install           # alias: pnpm i

# add a runtime dependency -> dependencies
npm install express
pnpm add express

# add a dev-only dependency -> devDependencies
npm install --save-dev jest     # npm i -D jest
pnpm add -D jest

# install a specific version
npm install [email protected]
npm install lodash@^4.17.0      # caret: 4.x
npm install lodash@~4.17.0      # tilde: 4.17.x

# global install (CLI tools)
npm install -g pm2
pnpm add -g pm2

npm スクリプト

npm run <name> 経由で実行されるのが、package.json のスクリプトです。特別なのが、start と test です(npm start / npm test)。自動的に実行されるのが、pre/post のフック(pretest、postbuild)です。基礎のコマンドへ引数を転送するには、-- を使いましょう。カスタムスクリプトのため「run」という単語をスキップできるのが、pnpm です。

nodejs
// package.json
{
  "scripts": {
    "start": "node index.js",
    "dev": "node --watch index.js",
    "test": "jest",
    "build": "tsc && vite build"
  }
}

# run a script
npm run dev          # npm run-script dev
pnpm dev             # pnpm has no "run" requirement

# "start" and "test" have shortcuts
npm start
npm test

# pre/post hooks run automatically
// "pretest": "npm run lint",
// "postbuild": "npm run deploy"

# pass extra args with --
npm run build -- --mode production

npx と pnpm dlx

グローバルインストールなしでパッケージのバイナリを実行するのが、npx です — ダウンロードし、実行し、破棄します。スキャフォルダ(create-vite)やローカルの node_modules/.bin のツールの実行に完璧です。インストール確認のスキップが、--yes です。pnpm 版が、pnpm dlx です。

nodejs
# run a one-off command without installing globally
npx create-vite my-app
npx cowsay "hello"

# pin a version
npx prettier@3 --write .

# pnpm equivalent
pnpm dlx create-vite my-app

# execute a local bin from node_modules
npx jest            # runs ./node_modules/.bin/jest

# never prompt, always download latest
npx --yes create-react-app my-app

バージョニングとロックファイル

SemVer:破壊的変更が MAJOR、機能が MINOR、修正が PATCH です。npm のデフォルトであり minor+patch の更新を許すのが、^(caret)で、patch だけが ~(tilde)です。再現可能なインストールのため、完全な依存ツリーを固定するのが、ロックファイル(package-lock.json)です — 速度と安全のため、CI では npm ci を使いましょう。

nodejs
# semantic versioning: MAJOR.MINOR.PATCH
# 1.4.2 -> 1:breaking 4:feature 2:fix
"^1.4.2"  # >=1.4.2 <2.0.0  (caret, default)
"~1.4.2"  # >=1.4.2 <1.5.0  (tilde)
"1.4.2"   # exact 1.4.2
">=1.4.0 <2.0.0" # range

# lockfiles pin the installed tree
npm install       # writes/updates package-lock.json
pnpm install      # writes pnpm-lock.yaml
yarn install      # writes yarn.lock

# install exactly as locked (CI)
npm ci            # clean install from lockfile

# find outdated deps
npm outdated
npm update        # update within ^ ranges

公開とライフサイクル

パッケージをレジストリへアップロードするのが、npm publish です。バージョンを上げ、git タグを作り、コミットするのが、npm version です。リリース時のビルド/テストを自動化するのが、ライフサイクルフック(prepublishOnly、postpublish)です。非公開化が許されるのは 72 時間以内だけです — 古いバージョンには、npm deprecate を推奨しましょう。

nodejs
# login once
npm login

# publish to the registry
npm publish
npm publish --access public   # scoped default restricted

# bump version (updates package.json + tag + commit)
npm version patch   # 1.0.0 -> 1.0.1
npm version minor   # 1.0.0 -> 1.1.0
npm version major   # 1.0.0 -> 2.0.0

# lifecycle scripts (in package.json)
// "prepublishOnly": "npm test && npm run build",
// "prepublish": "npm run build",
// "postpublish": "git push --tags"

# unpublish within 72h
npm unpublish [email protected]
04

ファイルシステム(fs)

ファイルの読み取り

fs が提供するのは、sync(readFileSync)、コールバック(readFile)、promise(fs/promises の readFile)の API です。イベントループをブロックするのが sync 呼び出しであるため、サーバーでは避けましょう。async/await のモダンな選択が、fs/promises です。エンコーディングなしでは、readFile が Buffer を返します。

nodejs
const fs = require('fs');

// synchronous (blocks the event loop)
const text = fs.readFileSync('data.txt', 'utf8');
const buf = fs.readFileSync('image.png');  // Buffer

// asynchronous with callback (error-first)
fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) return console.error(err);
  console.log(data);
});

// async with fs/promises (preferred)
const fsp = require('fs/promises');
async function read() {
  const text = await fsp.readFile('data.txt', 'utf8');
  return text;
}

ファイルの書き込み

デフォルトでファイル全体を置き換えるのが、writeFile です。挙動を変えるのが、flag オプションです:追記が 'a'、ファイルが既に存在すれば失敗するのが 'wx'(EEXIST)— アトミックなファイル作成に有用です。書き込みの前には JSON を文字列化しましょう。ブロックするのが sync の書き込みなので、fs/promises を推奨します。

nodejs
const fs = require('fs');
const fsp = require('fs/promises');

// sync
fs.writeFileSync('out.txt', 'hello');

// async callback
fs.writeFile('log.txt', 'line1\n', err => {
  if (err) throw err;
});

// promise
await fsp.writeFile('config.json', JSON.stringify(cfg, null, 2));

// flags: 'w' write (default), 'a' append, 'wx' fail if exists
await fsp.writeFile('new.txt', 'x', { flag: 'wx' }); // throws if exists

ディレクトリ

mkdir -p を模倣するのが、{ recursive: true } 付きの mkdir です。エントリを一覧するのが、readdir で、余分な stat 呼び出しを避ける isDirectory()/isFile() を持つ Dirent オブジェクトを返すのが、{ withFileTypes: true } です。空でないディレクトリのため rmdir を置き換えるのが、recursive+force 付きの fsp.rm です(Node 14+)。

nodejs
const fsp = require('fs/promises');

// create (recursive like mkdir -p)
await fsp.mkdir('a/b/c', { recursive: true });

// list entries
const entries = await fsp.readdir('.');
// ['app.js', 'data', 'package.json']

// list with type info
const detailed = await fsp.readdir('.', { withFileTypes: true });
detailed.forEach(e => console.log(e.name, e.isDirectory()));

// remove
await fsp.rmdir('empty');             // empty dir only
await fsp.rm('folder', { recursive: true, force: true }); // rm -rf

// sync versions exist too: mkdirSync, readdirSync, rmSync

ファイルの統計とメタデータ

size、mtime、タイプのヘルパーを持つ Stats オブジェクトを返すのが、stat() です。fs.exists(非推奨)を使ってはいけません。競合フリーの存在チェックには、try/catch 内の access() を使いましょう — とはいえ、直接ファイルを開く方がより安全です。変更イベントを出すのが fsWatch ですが、プラットフォーム間で一貫しないことがあります。

nodejs
const fsp = require('fs/promises');

const stats = await fsp.stat('data.txt');
stats.isFile();          // true
stats.isDirectory();     // false
stats.size;              // bytes
stats.mtime;             // Date modified
stats.birthtime;         // Date created
stats.mode;              // permission bits

// check existence (avoid existsSync for races)
try {
  await fsp.access('config.json');
  console.log('exists');
} catch {
  console.log('missing');
}

// watch for changes
const watcher = fs.watch('.');
watcher.on('change', (eventType, filename) => {});

fs.promises API

すべての fs メソッドの promise ベースの版を提供するのが、fs/promises(Node 10+)で、async/await に理想的です。メモリ効率の良いディレクトリ走査のための非同期イテレータを返すのが、opendir() です。移植可能なパスのためには、path.join と組み合わせましょう。すべてのメソッドがエラー時に投げるため、try/catch で包みましょう。

nodejs
const fsp = require('fs/promises');
const path = require('path');

// full async/await file operations
async function loadConfig() {
  const file = path.join(__dirname, 'config.json');
  const raw = await fsp.readFile(file, 'utf8');
  return JSON.parse(raw);
}

async function saveConfig(cfg) {
  const file = path.join(__dirname, 'config.json');
  await fsp.writeFile(file, JSON.stringify(cfg, null, 2));
}

// iterate directory tree
for await (const entry of await fsp.opendir('.')) {
  console.log(entry.name);
}

追加、改名、削除

末尾への内容の追加(欠けていればファイルを作る)が、appendFile です。同じファイルシステム上ではアトミックであり、ファイルの移動に使われるのが、rename です。ファイルの削除が unlink で、内容のコピーが copyFile、ディレクトリを再帰的に扱うのが、fsp.cp(Node 16+)です。与えられた長さへファイルをリサイズするのが、truncate です。

nodejs
const fsp = require('fs/promises');

// append to a file (creates if missing)
await fsp.appendFile('log.txt', new Date() + ' started\n');

// atomic rename (also for moving)
await fsp.rename('old.txt', 'new.txt');
// move across dirs
await fsp.rename('a/x.txt', 'b/x.txt');

// delete a file
await fsp.unlink('temp.txt');

// copy
await fsp.copyFile('src.txt', 'dest.txt');
// or fsp.cp('src', 'dest', { recursive: true })

// truncate to a length
await fsp.truncate('data.bin', 1024);
05

パスの処理

path.join と path.resolve

プラットフォームの区切りを使いセグメントを連結し、結果を正規化するのが、path.join です。process.cwd() から始まる絶対パスを作るのが、path.resolve で、絶対のセグメントが前のセグメントを破棄します。Windows と POSIX でパスが機能するよう、文字列連結の代わりに必ず path.join を使いましょう。

nodejs
const path = require('path');

// join segments with the OS separator
path.join('src', 'utils', 'file.js');
// 'src/utils/file.js' (Linux)  or 'src\utils\file.js' (Windows)

// resolve to an ABSOLUTE path (from cwd)
path.resolve('src', 'file.js');
// '/current/dir/src/file.js'

// resolve with absolute segment resets
path.resolve('/a', 'b', '/c', 'd');   // '/c/d'

// normalize '..' and '.' segments
path.normalize('a/b/../c/./d');        // 'a/c/d'

// never hardcode '/' — use path.join for portability

dirname、basename、extname

ディレクトリを返すのが dirname で、(省略可能に拡張子を剥ぎ取る)ファイル名を返すのが basename、最後の拡張子(ドットを含む)を返すのが extname です。.tar.gz のような複数パートの拡張子には、最後の .gz だけが返されます。これらは純粋な文字列操作で — ファイルシステムへのアクセスはありません。

nodejs
const path = require('path');
const file = '/app/src/utils/helper.js';

path.dirname(file);    // '/app/src/utils'
path.basename(file);   // 'helper.js'
path.basename(file, '.js'); // 'helper' (strip ext)
path.extname(file);    // '.js'
path.extname('archive.tar.gz'); // '.gz' (last ext)

// for the current file (CommonJS)
path.dirname(__filename);  // current dir
path.basename(__filename); // current file name

path.parse と format

パスを root、dir、base、name、ext へ分割するのが、path.parse で、再構成するのが、path.format です。あるディレクトリから別のディレクトリへ行くのに必要な相対パスを計算するのが、path.relative です。一緒に、面倒な文字列のスライシングでなく宣言的なパス操作ができます。

nodejs
const path = require('path');

// decompose a path into parts
const p = path.parse('/app/src/helper.test.js');
// { root: '/', dir: '/app/src',
//   base: 'helper.test.js', name: 'helper.test', ext: '.js' }

// rebuild from a parsed object
const rebuilt = path.format({
  dir: '/app/dist',
  name: 'bundle',
  ext: '.min.js'
});
// '/app/dist/bundle.min.js'

// get the relative path from A to B
path.relative('/a/b/c', '/a/x');   // '../../x'

クロスプラットフォームのパス

OS ごとに異なるのが、path.sep と path.delimiter です。ホスト OS にかかわらず、特定のパーサを強制するのが、path.win32 と path.posix で — 他のプラットフォームからのパスの処理に便利です。':' や ';' をハードコードせず、PATH 風の env 変数を移植可能に分割するには、path.delimiter を使いましょう。

nodejs
const path = require('path');

// platform-specific values
path.sep;           // '/' (POSIX) or '\\' (Windows)
path.delimiter;     // ':' (POSIX) or ';' (Windows)

// force a specific platform's behavior
path.win32.join('a', 'b');   // 'a\\b'
path.posix.join('a', 'b');   // 'a/b'

// parse PATH env var portably
process.env.PATH.split(path.delimiter).forEach(dir => {
  console.log(dir);
});

// check if absolute
path.isAbsolute('/etc');     // true
path.isAbsolute('a/b');      // false
path.win32.isAbsolute('C:\\'); // true

File URL と pathToFileURL

file:// URL で識別されるのが、ES Modules です。通常のパスを動的な import() のための URL へ変えるのが、url.pathToFileURL で、逆方向が url.fileURLToPath です。ESM では、import.meta.url が既に file URL であるため — __filename を複製するには、fileURLToPath でパスへ変換しましょう。

nodejs
const path = require('path');
const url = require('url');

// convert a path to a file:// URL (ESM import)
const fileUrl = url.pathToFileURL('/app/src/mod.mjs');
// URL { href: 'file:///app/src/mod.mjs' }

// and back
const p = url.fileURLToPath('file:///app/src/mod.mjs');
// '/app/src/mod.mjs'

// in ESM, import.meta.url is already a file URL
// convert to a normal path:
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
06

HTTP サーバー

基本の HTTP サーバー

サーバーを返すのが、http.createServer です。すべてのリクエストを扱うのが、コールバックです。ステータスコードとヘッダーの設定が res.writeHead で、ボディの送信とレスポンスの終了が res.end です。与えられたポートで接続の受け付けを始めるのが、listen() です。イベントループ経由で 1 つの Node プロセスが多くの同時リクエストを扱います。

nodejs
const http = require('http');

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

// listen on a port
server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

// or with a host and backlog
server.listen(3000, '127.0.0.1', 511, () => {});

Request と Response

method、url、headers を公開するのが req で、statusCode/headers を設定し write+end できるのが、res です。レスポンスを終了するには、res.end を MUST で呼びましょう。大きなペイロードのためには、すべてをメモリへバッファしないため、res.write 経由でデータをストリーミングするか、Readable を res へパイプしましょう。

nodejs
const http = require('http');

http.createServer((req, res) => {
  // request info
  console.log(req.method);   // 'GET'
  console.log(req.url);      // '/users?id=5'
  console.log(req.headers);  // { host, 'user-agent', ... }

  // response helpers
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.write('partial chunk\n');
  res.end(JSON.stringify({ ok: true }));
}).listen(3000);

// streaming a large response
res.writeHead(200);
readStream.pipe(res);   // pipe file -> response

ルーティングと URL のパース

Node には組み込みのルーターがありません — req.method と req.url 上の if/else で実装するか、pathname と searchParams をパースするため URL コンストラクタを使いましょう。本物のアプリには、Express かフレームワークのルーターへ手を伸ばしましょう。相対的な req.url のパースには、URL コンストラクタにベースが必要です。

nodejs
const http = require('http');
const { URL } = require('url');

http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');
  const path = url.pathname;
  const q = url.searchParams.get('id');

  if (req.method === 'GET' && path === '/') {
    res.end('home');
  } else if (path === '/users') {
    res.end('users');
  } else {
    res.writeHead(404);
    res.end('not found');
  }
}).listen(3000);

JSON と POST ボディの処理

ストリームとして届くのが、リクエストボディです — パースの前にチャンクを集めなければなりません。モダンなアプローチが、非同期イテレータのパターン(for await of req)です。JSON で応答するときは、必ず Content-Type: application/json を設定しましょう。メモリの枯渇を防ぐため、本番ではボディサイズに上限を設けましょう。

nodejs
const http = require('http');

http.createServer(async (req, res) => {
  if (req.method === 'POST') {
    // collect the streamed body
    const chunks = [];
    for await (const chunk of req) chunks.push(chunk);
    const body = JSON.parse(Buffer.concat(chunks).toString());

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ received: body }));
  }
}).listen(3000);

// test: curl -X POST localhost:3000 -d '{"a":1}'

サーバーのイベントとエラー

サーバーが EventEmitter です。'error' は扱わなければならず — EADDRINUSE がポートの占有を意味します。クライアントソケットごとに発火するのが、'connection' です。優雅なシャットダウンのためには、SIGTERM/SIGINT を listen し server.close() を呼び、プロセスが終わる前に進行中のリクエストが完了するようにしましょう。

nodejs
const server = http.createServer(handler);

server.on('listening', () => console.log('ready'));
server.on('connection', socket => console.log('client connected'));
server.on('error', err => {
  if (err.code === 'EADDRINUSE') {
    console.error('port 3000 already in use');
  }
});
server.on('close', () => console.log('server closed'));

// graceful shutdown
process.on('SIGTERM', () => {
  server.close(() => process.exit(0));
});

server.listen(3000);

HTTPS と HTTP クライアント

秘密鍵と証明書(Let's Encrypt からなど)が必要なのが、https.createServer です。外向きのリクエストには、Node 18+ がグローバルの fetch() を ship するため — 素の http.get のコールバック API よりこれを推奨しましょう。promise ベースであり、async/await、ヘッダー、ストリームに対応するのが、fetch です。

nodejs
// HTTPS server (needs TLS certs)
const https = require('https');
const fs = require('fs');

https.createServer({
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
}, handler).listen(443);

// HTTP client: simple GET
http.get('http://example.com', res => {
  let data = '';
  res.on('data', c => data += c);
  res.on('end', () => console.log(data));
});

// modern fetch (Node 18+, global, promise-based)
const res = await fetch('https://api.example.com');
const json = await res.json();
07

Express の基本

Express のセットアップと Hello World

最も人気のある Node の Web フレームワークが、Express です。ルートハンドラを登録するのが、app.get で、(Content-Type を自動検出し)レスポンスを送るのが、res.send です。サーバーを始めるのが、app.listen です。ルーティング、ミドルウェア、便利なヘルパーで、Node の http モジュールを包むのが、Express です。

nodejs
// install: npm install express
import express from 'express';

const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(PORT, () => {
  console.log(`Server on http://localhost:${PORT}`);
});

ルーティングとルートパラメータ

HTTP メソッド(get/post/put/delete)をパスへマッチさせるのが、Express です。URL セグメントを req.params へ取り込むのが、:id で、クエリ文字列の値を保持するのが、req.query です。同じパスのために複数のメソッドをチェーンさせるのが、app.route です。登録順にルートがマッチするため、汎用のルートの前に具体的なルートを定義しましょう。

nodejs
app.get('/users', (req, res) => res.send('list users'));
app.post('/users', (req, res) => res.send('create user'));

// URL parameters
app.get('/users/:id', (req, res) => {
  res.send(`user ${req.params.id}`);
});

// query strings: /search?q=node
app.get('/search', (req, res) => {
  res.send(`searching: ${req.query.q}`);
});

// chain handlers for one path
app.route('/book')
  .get((req, res) => res.send('get book'))
  .post((req, res) => res.send('add book'));

ミドルウェア

リクエストのサイクル中に動き、req、res、next を受け取る関数が、ミドルウェアです。次のハンドラへ続くには、next() を呼びましょう。グローバルに、またはパスの接頭辞にマウントするのが、app.use です。4 つの引数(最初が err)を持つのが、エラー処理のミドルウェアで、最後に登録されるべきです。

nodejs
// middleware: (req, res, next) => {}
app.use(express.json());          // parse JSON bodies
app.use(express.static('public'));// serve static files
app.use((req, res, next) => {     // custom logger
  console.log(req.method, req.url);
  next();                         // pass control forward
});

// mounted on a path
app.use('/api', (req, res, next) => {
  req.apiCall = true;
  next();
});

// error-handling middleware (4 args)
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Server Error');
});

リクエストデータ

適切なミドルウェアをマウントしたときだけ、Express がボディをパースします:JSON には express.json()、フォームには express.urlencoded()、ファイルアップロードには multer です。3 つの主なリクエストデータのソースが、req.params(URL セグメント)、req.query(クエリ文字列)、req.body(パースされたペイロード)です。

nodejs
// JSON body (needs express.json() middleware)
app.post('/api', (req, res) => {
  console.log(req.body);          // parsed JSON object
});

// URL params and query
app.get('/u/:id', (req, res) => {
  const { id } = req.params;
  const { tab } = req.query;
});

// form data (urlencoded)
app.use(express.urlencoded({ extended: true }));
app.post('/form', (req, res) => res.json(req.body));

// file uploads: use multer middleware
// const upload = multer({ dest: 'uploads/' });
// app.post('/upload', upload.single('file'), handler);

// headers & cookies
req.headers['user-agent'];
req.cookies;        // needs cookie-parser

静的ファイルの提供

ディレクトリからファイルを提供するのが、express.static です。フォールバックの挙動のため何度もマウントするか、パスを接頭辞に付けましょう。キャッシュヘッダーの設定が、maxAge のようなオプションです。MIME タイプを自動検出し、動画/音声のためのレンジリクエストに対応します。cwd 依存のバグを避けるため、必ず絶対パスを使いましょう。

nodejs
const path = require('path');

// serve files from /public at /
app.use(express.static('public'));
// GET /style.css -> public/style.css

// mount at a prefix
app.use('/static', express.static('public'));
// GET /static/style.css -> public/style.css

// multiple directories (fallthrough)
app.use(express.static('public'));
app.use(express.static('uploads'));

// absolute path + options
app.use(express.static(path.join(__dirname, 'public'), {
  maxAge: '1d',
  setHeaders: (res, filePath) => {
    if (filePath.endsWith('.html')) res.setHeader('Cache-Control', 'no-cache');
  }
}));

エラー処理と Router

エラー処理のミドルウェアをトリガーするのが、next(err) へエラーを渡すか、async ハンドラ内での throw です。1 つの中央の 4 引数のハンドラを最後に登録しましょう。ルートを別々のファイルへモジュール化するのが、express.Router() で — 大きな API をきれいに構成するため、app.use('/prefix', router) でマウントしましょう。

nodejs
// throw to jump to error middleware
app.get('/broken', (req, res, next) => {
  const err = new Error('boom');
  err.status = 400;
  next(err);              // or throw err (Express 4+)
});

// centralized error handler (last middleware)
app.use((err, req, res, next) => {
  const status = err.status || 500;
  res.status(status).json({ error: err.message });
});

// modular routing with express.Router()
const router = express.Router();
router.get('/', (req, res) => res.send('api root'));
router.get('/users', (req, res) => res.send('users'));
app.use('/api', router);  // mount at /api
08

Streams

Readable ストリーム

データを作るのが、Readable ストリームです。flowing モードでは、'data' イベントがチャンクを自動的に push し、paused モードでは、明示的に read() を呼びます。'error' は必ず扱いましょう — 未処理のエラーイベントがプロセスをクラッシュさせます。内部バッファサイズの制御が、highWaterMark です。

nodejs
const fs = require('fs');

// create a readable stream from a file
const rs = fs.createReadStream('big.log', { highWaterMark: 64 * 1024 });

// 'data' mode (flowing)
rs.on('data', chunk => {
  console.log('got', chunk.length, 'bytes');
});
rs.on('end', () => console.log('done'));
rs.on('error', err => console.error(err));

// paused mode: pull on demand
rs.on('readable', () => {
  let chunk;
  while ((chunk = rs.read()) !== null) {
    process(chunk);
  }
});

Writable ストリーム

データを消費するのが、Writable ストリームです。内部バッファが満杯のとき write() が false を返すため、backpressure を尊重するため、より書く前に 'drain' イベントを待ちましょう。これ以上データがないことを合図するのが end() で、すべてが流された後に発火するのが、'finish' です。それ自体が writable ストリームであるのが、process.stdout です。

nodejs
const fs = require('fs');
const ws = fs.createWriteStream('out.log');

// write returns false when the buffer is full (backpressure)
const ok = ws.write('line\n');
if (!ok) ws.once('drain', () => writeMore());

// signals completion
ws.end('final line\n');
ws.on('finish', () => console.log('all data flushed'));
ws.on('error', err => console.error(err));

// process.stdout is a writable stream
process.stdout.write('hello');

pipe と pipeline

自動 backpressure で Readable を Writable へ転送するのが、pipe() です。複数のストリームをチェーンし、(promises 版を推奨)エラーを適切に伝播し後始末するのが、stream.pipeline です — 途中のストリームのエラーで、.pipe() 単独がリソースを漏らします。手動の .pipe() のチェーンより必ず pipeline を推奨しましょう。

nodejs
const fs = require('fs');
const { pipeline } = require('stream/promises');

// pipe: readable -> writable (auto backpressure)
fs.createReadStream('in.txt')
  .pipe(fs.createWriteStream('out.txt'));

// pipeline: chain transforms, with error handling
const { Transform } = require('stream');
const upper = new Transform({
  transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); }
});

await pipeline(
  fs.createReadStream('in.txt'),
  upper,
  fs.createWriteStream('out.txt')
);
// pipeline rejects on error, unlike .pipe()

Transform ストリーム

入力を読み、処理し、変換された出力を出すのが、Transform ストリームです — パイプラインでのパース、圧縮、暗号化に完璧です。transform(chunk, enc, cb) を実装し、省略可能として flush(cb) を実装しましょう。Buffer の代わりにオブジェクトを push できるのが、objectMode です。既製の transform を提供するのが、zlib と crypto です。

nodejs
const { Transform } = require('stream');

// a Transform is both Readable and Writable
const csvToJson = new Transform({
  objectMode: false,
  transform(chunk, encoding, callback) {
    // convert each chunk
    const lines = chunk.toString().trim().split('\n');
    const json = lines.map(l => JSON.stringify(l.split(','))).join('\n');
    callback(null, json + '\n');
  },
  flush(callback) {
    callback(null, ']\n'); // finalize
  }
});

process.stdin.pipe(csvToJson).pipe(process.stdout);

// built-in transforms: zlib, crypto streams
const { createGzip } = require('zlib');
fs.createReadStream('log').pipe(createGzip()).pipe(fs.createWriteStream('log.gz'));

ストリームのモードと backpressure

pause()/resume() により、flowing と paused のモードの間で交代するのが、ストリームです。遅い消費者が生産者に遅くするよう合図するのが、backpressure です — 各チャンクを await することで、非同期反復(for await)がこれを自動処理し、最もきれいなモダンパターンです。Buffer でなく文字列を得るため、必ずエンコーディングを設定しましょう。

nodejs
const rs = fs.createReadStream('huge.bin');

// switch between modes
rs.pause();
rs.resume();
rs.setEncoding('utf8');

// respect backpressure manually
function writeChunk(ws, data) {
  if (!ws.write(data)) {
    rs.pause();
    ws.once('drain', () => rs.resume());
  }
}

// async iteration (Node 10+) — cleanest pattern
async function consume() {
  for await (const chunk of rs) {
    await handle(chunk);  // naturally respects backpressure
  }
}
consume();

カスタムストリーム

Readable/Writable/Duplex を継承し _read/_write を実装するか、既にあるデータのための、より簡単な Readable.from() を使いましょう。ストリームの終了を合図するのが、push(null) です。独立に読み書きできるのが、Duplex ストリームで(TCP ソケットのように)、出力が入力から派生する Duplex が、Transform です。

nodejs
const { Readable, Writable, Duplex } = require('stream');

// custom Readable: generate a counter
const counter = new Readable({
  read() {
    if (++this._n > 10) this.push(null);  // end
    else this.push(String(this._n));
  }
});
counter._n = 0;
counter.pipe(process.stdout);

// from an array / async iterable
Readable.from(['a', 'b', 'c']).pipe(process.stdout);

// a Duplex: both readable and writable (e.g. a socket)
class Echo extends Duplex {
  _read() {}
  _write(chunk, enc, cb) { this.push(chunk); cb(); }
}
09

Buffer

Buffer の作成

ゼロで満たされた(安全な)バッファを作るのが、Buffer.alloc です。速度のためにゼロ化をスキップするが古いメモリを漏らし得るのが、Buffer.allocUnsafe で — すべてのバイトを上書きするときだけ使いましょう。文字列/配列/バッファを変換するのが、Buffer.from です。セキュリティの懸念のため非推奨なのが、レガシーの「new Buffer()」コンストラクタです。

nodejs
// allocate zeroed bytes (SAFE)
const b1 = Buffer.alloc(8);            // <Buffer 00 00 00 00 00 00 00 00>

// allocate WITHOUT zeroing (faster, may contain old memory)
const b2 = Buffer.allocUnsafe(8);      // random old data!

// from a string with encoding
const b3 = Buffer.from('hello', 'utf8');
// <Buffer 68 65 6c 6c 6f>

// from an array of bytes
const b4 = Buffer.from([0x48, 0x49]);  // 'HI'

// from another buffer (copy)
const b5 = Buffer.from(b3);

// NEVER use new Buffer() — deprecated and unsafe

読み取りと書き込み

生のバイトを保持するのが、Buffer です。明示的なサイズ(UInt8/16/32)とエンディアン(BE/LE)付きで read/write のメソッドを使いましょう。ネットワークバイト順が、ビッグエンディアンで、x86 で一般的なのが、リトルエンディアンです。バイトを文字列へデコードするのが、toString(encoding, start, end) です。以前のバイトの上書きを避けるため、必ずオフセットを渡しましょう。

nodejs
const buf = Buffer.alloc(8);

// write numeric values at an offset
buf.writeUInt8(255, 0);       // 1 byte
buf.writeUInt16BE(0x1234, 1); // 2 bytes, big-endian
buf.writeInt32LE(1000, 3);    // 4 bytes, little-endian

// read them back
buf.readUInt8(0);             // 255
buf.readUInt16BE(1);          // 0x1234
buf.readInt32LE(3);           // 1000

// string read/write
buf.write('Hi', 0, 'utf8');
buf.toString('utf8', 0, 2);   // 'Hi'

連結と比較

バッファの配列を結合するのが、Buffer.concat です(省略可能な総長のヒントがパフォーマンスを改善します)。バイトシーケンスを比較できるのが、equals/compare で、サブバッファを見つけるのが、indexOf/includes です — バイナリプロトコルで有用です。あるバッファへスライスをコピーするのが、copy(target, targetStart, sourceStart, sourceEnd) です。

nodejs
const a = Buffer.from('foo');
const b = Buffer.from('bar');

// concatenate buffers
const c = Buffer.concat([a, b]);   // 'foobar'
Buffer.concat([a, b], 6);          // total length hint

// compare
Buffer.compare(a, b);        // -1 (a < b), 0, or 1
a.equals(b);                  // false

// find a sub-buffer
const big = Buffer.from('hello world');
big.indexOf(Buffer.from('world'));   // 6
big.includes(Buffer.from('hello'));  // true

// copy bytes
const target = Buffer.alloc(5);
big.copy(target, 0, 0, 5);   // copy first 5 bytes

エンコーディング

文字列とバイトの間をマッピングするのが、エンコーディングです。テキストのデフォルトが utf8 で、テキスト中のバイナリ(データ URL、ハッシュ、転送)で一般的なのが、base64/hex です。バイトサイズを与えるのが、Buffer.byteLength です(utf8 ではマルチバイト文字が 1 バイトより多く数えられます)— バッファのサイジングには、string.length でなくこれを使いましょう。

nodejs
const text = 'Hello, 世界';

// string -> buffer (encode)
const utf8 = Buffer.from(text, 'utf8');
const base64 = Buffer.from(text).toString('base64');
const hex = Buffer.from(text).toString('hex');
const latin1 = Buffer.from(text, 'latin1');

// buffer -> string (decode)
utf8.toString('utf8');     // 'Hello, 世界'
Buffer.from(base64, 'base64').toString('utf8');
Buffer.from(hex, 'hex').toString('utf8');

// common encodings: utf8, utf16le, latin1, ascii,
//   base64, base64url, hex
Buffer.byteLength('世界', 'utf8');  // 6 bytes (not 2)

Buffer と TypedArray

Uint8Array を継承するため、Buffer が TypedArray が機能するどこでも機能します。メモリを共有するのが、Buffer.from(arrayBuffer) です(コピーなし)— しかし Buffer がより大きいプールされた ArrayBuffer をスライスし得るため、ビューを作るときは必ず byteOffset/byteLength を尊重しましょう。これで、細かい数値アクセスのために、Buffer の API を DataView と混ぜられます。

nodejs
// Buffer is a subclass of Uint8Array
const buf = Buffer.from([1, 2, 3]);
buf instanceof Uint8Array;  // true

// share memory with TypedArrays without copying
const u8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
view.getInt32(0);

// Buffer from an ArrayBuffer
const ab = new ArrayBuffer(8);
const buf2 = Buffer.from(ab);

// note: a Buffer's underlying buffer may be larger
// (allocUnsafe pools) -> always use byteOffset

Slice、Fill、Swap

元のメモリを共有するビューを返すのが、subarray(または slice)です — 変更が両方に影響します。バッファ全体にわたりバイトか繰り返す文字列を書くのが、fill です。エンディアン変換のために、その場でバイト順を逆にするのが、swap16/swap32 です。イテラブルであり、各バイト値 0〜255 を出すのが、Buffer です。

nodejs
const buf = Buffer.from('abcdef');

// slice shares memory (no copy) — like subarray
const s = buf.subarray(1, 4);   // 'bcd'
s[0] = 88;                      // mutates buf too -> 'aXcdef'

// fill with a value or pattern
Buffer.alloc(4).fill(0xff);            // <Buffer ff ff ff ff>
Buffer.alloc(6).fill('ab');            // 'ababab'

// reverse byte order in place (for endianness swaps)
const n = Buffer.from([0x01, 0x02, 0x03, 0x04]);
n.swap16();  // swaps pairs: <Buffer 02 01 04 03>

// iterate with for...of
for (const byte of buf) console.log(byte);  // 97, 98, ...
10

EventEmitter

イベントの作成と発火

Node の pub/sub の核心が、EventEmitter です。イベントを発火するのが、emit(eventName, ...args) で、購読するのが、on() です。それを継承するのが、多くの組み込みクラス(streams、http サーバー)です。任意の文字列がイベント名ですが、'error' が特殊です。登録順に同期的に呼ばれるのが、リスナーです。

nodejs
const { EventEmitter } = require('events');

class Clock extends EventEmitter {
  start() {
    this.emit('start', Date.now());          // emit with args
    setInterval(() => this.emit('tick', new Date()), 1000);
  }
}

const clock = new Clock();
clock.on('tick', date => console.log('tick', date));
clock.on('start', ts => console.log('started at', ts));
clock.start();

// on() == addListener; once() fires only once

once と removeListener

発火後に自動的に取り除かれるリスナーを登録するのが、once() です — 1 回限りのセットアップに最適です。リスナーを取り除くには、正確な関数への参照を保たなければなりません(矢印関数が毎回新しい参照を作ります)。1 つかすべてのイベントのリスナーを消去するのが、removeAllListeners です。removeListener の別名が、off です。

nodejs
const ee = new EventEmitter();

// once: auto-removed after first fire
ee.once('init', () => console.log('init fired'));

// remove a specific listener (need the same function ref)
const handler = () => console.log('hi');
ee.on('msg', handler);
ee.off('msg', handler);          // off() == removeListener

// remove all listeners for an event (or all events)
ee.removeAllListeners('msg');
ee.removeAllListeners();         // everything

// inspect
ee.listenerCount('msg');
ee.eventNames();                 // ['msg', 'init']

Error イベント

リスナーが登録されていない状態で 'error' イベントが出ると、Node が投げプロセスをクラッシュさせます。EventEmitter へ必ずエラーハンドラを付けましょう — ストリームと HTTP サーバーには特にです。非同期リスナーからの拒否された promise を「error」イベントへルートするのが、captureRejections(Node 12+)です。

nodejs
const ee = new EventEmitter();

// 'error' is special: if unhandled, it CRASHES the process
ee.on('error', err => {
  console.error('caught:', err.message);
});

// later, emit an error safely
ee.emit('error', new Error('something broke'));

// guard against crashes from unhandled errors
// (monitor with the static capture)
EventEmitter.captureRejections = true; // for async handlers

// always register an error listener on streams/http

非同期リスナー

同期的にリスナーを呼ぶのが、EventEmitter です。そのため、非同期リスナーの promise は await されず — 確定する前に emit() が返ります。単一のイベントを promise として await するには、once(ee, name) を使いましょう。サイレントに失われる代わりに、拒否された非同期リスナーが「error」イベントをトリガーするよう、captureRejections を有効化しましょう。

nodejs
const ee = new EventEmitter();

// listeners run synchronously; await doesn't pause the chain
ee.on('save', async () => {
  await fs.promises.writeFile('x', 'y');
  console.log('saved');
});
ee.emit('save');  // returns before the await finishes

// wait for async listeners in sequence
const { once } = require('events');
async function waitForReady() {
  await once(ee, 'ready');   // promise resolves on first 'ready'
  console.log('now ready');
}

// handle async errors properly
EventEmitter.captureRejections = true;
ee.on('job', async () => { throw new Error('boom'); });
ee.on('error', err => console.error(err));

イベントの命名と newListener

リスナーが追加・削除されるとき出される特殊なイベントが、newListener と removeListener で — フックやプロファイリングに有用です。リーク検出のしきい値(デフォルト 10)を上げるのが、setMaxListeners です。警告の通常の意味は、リスナーの後始末を忘れたことです。タイプミスを防ぐため、イベント名には Symbol か定数を使いましょう。

nodejs
const ee = new EventEmitter();

// special events fired by EventEmitter itself
ee.on('newListener', (event, listener) => {
  console.log('listener added for', event);
});
ee.on('removeListener', (event, listener) => {
  console.log('listener removed for', event);
});

// limit listener count to catch leaks
ee.setMaxListeners(20);
ee.getMaxListeners();          // 20
// MaxListenersExceededWarning fires if exceeded

// convention: camelCase event names, 'error' reserved
// prefer symbols/const strings to avoid typos
const READY = Symbol('ready');
ee.emit(READY);
11

子プロセス

exec(シェル、バッファリング)

シェル経由でコマンドを実行し stdout/stderr をバッファするのが、exec() です — すべての出力を一度に欲しい、短いコマンドに最良です。シェルを spawn するため、glob とパイプを展開します。コマンド文字列へユーザー入力を補間してはいけません — それはコマンドインジェクションの脆弱性であり、代わりに args 配列付きの spawn を使いましょう。

nodejs
const { exec } = require('child_process');

// runs a command in a shell, buffers all output
exec('ls -la', (err, stdout, stderr) => {
  if (err) { console.error('failed:', err); return; }
  console.log(stdout);    // full stdout as a string
  console.error(stderr);
});

// promisified (Node 12+)
const { promisify } = require('util');
const execP = promisify(exec);
const { stdout } = await execP('git rev-parse HEAD');

// WARNING: shell interpolation = injection risk!
// NEVER: exec(`rm ${userInput}`)

spawn(ストリーミング、シェルなし)

args 配列(シェルなし)付きでプロセスを起動し stdout/stderr をストリーミングするのが、spawn() です — 大きい、または長時間実行の出力にとって、安全でメモリ効率が良いです。args が(シェルを通さず)直接渡されるため、glob の展開もインジェクションのリスクもありません。パイプラインのため、子のストリームを他のストリームへパイプしましょう。

nodejs
const { spawn } = require('child_process');

// no shell by default -> safe, stream-based
const child = spawn('ls', ['-la', '/tmp']);

child.stdout.on('data', chunk => process.stdout.write(chunk));
child.stderr.on('data', chunk => process.stderr.write(chunk));
child.on('close', code => console.log('exit code', code));
child.on('error', err => console.error('failed to spawn', err));

// pipe streams directly
const gzip = spawn('gzip');
process.stdin.pipe(gzip.stdin);
gzip.stdout.pipe(process.stdout);

execFile と fork

シェルなしで実行ファイルを実行するのが、execFile です — args 付きの既知のバイナリの実行には、exec より安全です。Node プロセスを spawn し組み込みの IPC チャネル(send/on('message'))を開くのが、fork() で、cluster や worker_threads 風の、Node プロセス間のメッセージパッシングの基礎です。

nodejs
const { execFile, fork } = require('child_process');

// execFile: like exec but no shell (safer, slight overhead saving)
execFile('node', ['--version'], (err, stdout) => {
  console.log(stdout.trim());   // v20.x.x
});

// fork: spawn another Node process with an IPC channel
const worker = fork('./worker.js');
worker.send({ task: 'compute', n: 100 });
worker.on('message', msg => console.log('result:', msg));
worker.on('exit', code => console.log('worker exited', code));

// in worker.js:
// process.on('message', msg => { process.send(result); });

stdio と引数

子の標準ストリームを制御するのが、stdio です:親のターミナルを共有するのが「inherit」(npm スクリプトに最適)、破棄が「ignore」、取り込みが「pipe」です。親を生き延びるバックグラウンドプロセスを spawn するのが、detached + unref() です。引数を配列として渡しましょう — spawn があなたのために引用するため、スペースと特殊文字が安全です。

nodejs
const { spawn } = require('child_process');

// control stdio: 'pipe' (default), 'inherit', 'ignore', or fd
const child = spawn('npm', ['test'], {
  stdio: 'inherit'     // child uses parent's stdin/stdout/stderr
});

// per-stream: [stdin, stdout, stderr]
spawn('cat', [], { stdio: ['pipe', process.stdout, 'ignore'] });

// set env, cwd, and detached background process
const bg = spawn('node', ['server.js'], {
  cwd: '/app',
  env: { ...process.env, NODE_ENV: 'production' },
  detached: true          // runs independently of parent
});
bg.unref();               // let parent exit without waiting

// pass arguments safely as array (no shell parsing)
spawn('echo', ['hello world']);  // one arg, no quotes needed

終了コードとシグナル

code(シグナルで殺されたなら null)と signal(通常終了では null)を報告するのが、「exit」イベントです。すべての stdio ストリームが閉じた後に発火するのが、「close」で — 出力をパイプしストリームが流されたことを知る必要があるときに使いましょう。シグナルを送るのが kill() で、優雅なのが SIGTERM で、捕捉不能なのが、SIGKILL です。

nodejs
const child = spawn('sleep', ['60']);

// 'exit' fires with code + signal
child.on('exit', (code, signal) => {
  if (code === 0) console.log('success');
  else if (signal) console.log('killed by', signal);
  else console.log('failed with code', code);
});

// send a signal to the child (SIGTERM by default)
setTimeout(() => child.kill('SIGTERM'), 1000);
child.kill();             // default SIGTERM
child.kill('SIGKILL');    // force-kill (cannot be caught)

// 'close' vs 'exit': 'close' fires after streams are closed
child.on('close', code => console.log('streams closed', code));

// check if process is still running
child.killed;             // true after kill() called
12

Cluster

基本のクラスタリング

1 つのポートを共有する複数の Node プロセスを fork でき、CPU コアをまたいでスケールするのが、cluster です。worker を fork するのが、プライマリです(通常 os.cpus().length)。同じスクリプトを実行する完全な Node プロセスが、各 worker です。耐性のため「exit」で worker を再起動しましょう。ロジックを分岐させるのが、cluster.isPrimary(旧 isMaster)です。

nodejs
const cluster = require('cluster');
const http = require('http');
const os = require('os');

if (cluster.isPrimary) {            // old: isMaster
  // fork one worker per CPU core
  for (let i = 0; i < os.cpus().length; i++) cluster.fork();

  cluster.on('exit', (worker, code) => {
    console.log(`worker ${worker.process.pid} died`);
    cluster.fork();                 // restart it
  });
} else {
  // workers share the same port
  http.createServer((req, res) => res.end('hi'))
    .listen(3000);
  console.log('worker started', process.pid);
}

Worker の管理

「online」(プロセス開始)、「listening」(サーバー束縛)、「disconnect」、「exit」のイベント経由で、プライマリが worker を追跡します。worker を殺す前に接続を排水するのが、disconnect() で — ダウンタイムゼロのリロードに使いましょう。メッセージや閉鎖ができるよう、worker の ID を Worker オブジェクトへマッピングするのが、cluster.workers です。

nodejs
cluster.on('online', worker => {
  console.log('worker responsive', worker.id);
});

cluster.on('listening', (worker, address) => {
  console.log('worker bound to', address.port);
});

cluster.on('disconnect', worker => {
  console.log('worker disconnected', worker.id);
});

// gracefully shut down a worker
const w = cluster.workers[1];
w.disconnect();            // stop accepting connections, then exit
w.send('shutdown');        // custom message

// iterate all workers
for (const id in cluster.workers) {
  cluster.workers[id].send({ cmd: 'reload' });
}

共有サーバーのポート

すべての worker が同じポートで listen し、入ってくる接続をプライマリがロードバランスします。均等に配るのが、SCHED_RR(round-robin、ほとんどのプラットフォームのデフォルト)で、OS に委ねるのが、SCHED_NONE です。worker 間で状態は共有「されません」 — 共有のセッション/キャッシュには、Redis かデータベースを使いましょう。

nodejs
const cluster = require('cluster');
const http = require('http');

if (cluster.isPrimary) {
  cluster.schedulingPolicy = cluster.SCHED_RR;  // round-robin (default on non-Windows)
  cluster.fork();
  cluster.fork();
} else {
  // all workers call listen(3000) — primary load-balances
  http.createServer((req, res) => {
    res.end(`handled by ${process.pid}`);
  }).listen(3000);
}

// SCHED_RR: primary distributes connections (default)
// SCHED_NONE: OS balances (may be uneven)

Worker のライフサイクルと IPC

IPC チャネルを開くのが、cluster.fork() です(child_process.fork のように):プライマリと worker の間で JSON を交換するのが、worker.send と process.on('message') です。ジョブの dispatch や優雅なシャットダウンの合図に使いましょう。CPU が重い作業には、worker_threads も検討しましょう。これがメモリを共有し IPC のオーバーヘッドを避けます。

nodejs
// primary -> worker messaging
if (cluster.isPrimary) {
  const worker = cluster.fork();
  worker.on('message', msg => console.log('from worker:', msg));
  worker.send({ task: 'heavy-compute' });
} else {
  process.on('message', msg => {
    console.log('from primary:', msg);
    // do work, then report back
    process.send({ done: true, result: 42 });
  });
}

// graceful shutdown signal
process.on('message', msg => {
  if (msg === 'shutdown') {
    server.close(() => process.exit(0));
  }
});

優雅なリロード(ダウンタイムゼロ)

worker を一度に 1 つずつリロードし、アプリが決して落ちないのが、ローリング再起動です:worker を disconnect し(新しい接続の受け付けを止めます)、排水後に終わるのを待ち、それから置き換えを fork します。トリガーするのが、SIGHUP です。worker ごとの「shutdown」メッセージと常に組み合わせ、各 worker が、進行中のリクエストが終わった後にだけ、サーバーを閉じて終了するようにしましょう。

nodejs
// rolling restart: reload workers one at a time
function reload() {
  const workers = Object.values(cluster.workers || {});
  let i = 0;
  const next = () => {
    if (i >= workers.length) return;
    const w = workers[i++];
    w.send('shutdown');                 // tell worker to drain
    w.disconnect();                     // stop accepting connections
    w.once('exit', () => {
      cluster.fork();                   // replacement ready
      next();                           // move to the next
    });
  };
  next();
}

// trigger reload on SIGHUP
process.on('SIGHUP', reload);

// in the worker: finish in-flight requests then exit
process.on('message', msg => {
  if (msg === 'shutdown') server.close(() => process.exit(0));
});
13

非同期プログラミング

コールバックとエラーファーストの慣例

Node のクラシックな非同期パターンが、エラーファーストのコールバックです:最初の引数がエラー(成功なら null)で、続く引数が結果です。err を最初に必ず確認し、失敗時に早く返りましょう。このスタイルがネストでうまくスケールしないことは — コールバック地獄として知られ — モダンなコードが Promises と async/await を使う理由です。

nodejs
// Node callbacks: (err, result) => {}
const fs = require('fs');

fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) return console.error('read failed', err);
  console.log(data);
});

// custom error-first function
function divide(a, b, cb) {
  if (b === 0) return cb(new Error('divide by zero'));
  cb(null, a / b);
}

divide(10, 2, (err, result) => {
  if (err) return console.error(err);
  console.log(result);   // 5
});

Promises

未来の値を表すのが、Promise です。成功を扱うのが then() で、拒否を扱うのが catch()、どちらでも動くのが finally() です。値を順に変換するには、then() をチェーンしましょう。エラーファーストのコールバック関数を Promise を返すものへ変えるのが、util.promisify です — レガシー API と async/await の橋渡しです。

nodejs
// create a promise
const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('done'), 100);
});

// consume with then/catch/finally
p.then(val => console.log(val))      // 'done'
 .catch(err => console.error(err))
 .finally(() => console.log('settled'));

// chain transforms
fetch(url)
  .then(r => r.json())
  .then(data => render(data));

// convert callback APIs
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const text = await readFile('x.txt', 'utf8');

async/await

非同期コードが同期に見えるようにするのが、async/await です。Promise を返すのが、async 関数で、確定まで止めるのが、await です。拒否を扱うため、await された呼び出しを try/catch で包みましょう。ES モジュールでは(フラグ付きで CommonJS でも)、トップレベルの await が許され、async IIFE のラッパーの必要性をなくします。

nodejs
// async functions always return a Promise
async function loadUser(id) {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error('not found');
  return res.json();
}

// consume with try/catch
try {
  const user = await loadUser(5);
  console.log(user);
} catch (err) {
  console.error('failed:', err);
}

// top-level await works in ESM and CommonJS (Node 14.8+)
const config = await loadConfig();

Promise.all と allSettled

promises を並行に実行し結果の配列で解決するのが、Promise.all ですが、ANY の promise が拒否すれば即座に拒否します(fast-fail)— すべてが成功しなければならないときに使いましょう。結果にかかわらずすべての promise を待ち、{status, value/reason} のオブジェクトを返すのが、Promise.allSettled です — 部分的な成功が許容されるときに最良です。

nodejs
// all: run in parallel, reject fast on first failure
const [a, b, c] = await Promise.all([
  fetch('/a').then(r => r.json()),
  fetch('/b').then(r => r.json()),
  fetch('/c').then(r => r.json())
]);

// allSettled: wait for ALL, never rejects
const results = await Promise.allSettled([
  fetch('/x'),
  fetch('/y'),
  fetch('/z')
]);
results.forEach(r => {
  if (r.status === 'fulfilled') console.log(r.value);
  else console.error(r.reason);   // rejected reason
});

Promise.race と Promise.any

最初に確定した promise で解決か拒否するのが、Promise.race です — タイムアウトやミラーのレースに有用です。最初の成功で解決し、すべての promise が失敗したときだけ拒否するのが、Promise.any です(AggregateError)— 1 つの健康的なレスポンスで十分な、冗長なエンドポイントに理想的です。

nodejs
// race: first to SETTLE (resolve or reject) wins
const fastest = await Promise.race([
  fetch('/primary'),
  fetch('/mirror'),
  timeout(5000)
]);

// any: first to FULFILL wins; rejects only if ALL reject
const alive = await Promise.any([
  fetch('/node1'),
  fetch('/node2'),
  fetch('/node3')
]);

// implement a timeout with race
function withTimeout(p, ms) {
  return Promise.race([
    p,
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('timeout')), ms))
  ]);
}

逐次対並列

ループ内での await が、逐次実行されます(遅い)。並列性のために、promises の配列へ map し Promise.all を呼びましょう(速いですが、無制限の同時実行がリソースを圧迫し得ます)。並行作業を絞るのが、同時実行を制限するプールです — レート制限された API の呼び出しや、数千のアイテムにわたる重い I/O には、不可欠です。

nodejs
// SEQUENTIAL: one after another (slow)
const results = [];
for (const url of urls) {
  results.push(await fetch(url).then(r => r.json()));
}

// PARALLEL: fire all, await together (fast)
const results = await Promise.all(
  urls.map(u => fetch(u).then(r => r.json()))
);

// THROTTLED: limit concurrency with a pool
async function mapLimit(items, limit, fn) {
  const ret = [];
  const executing = [];
  for (const item of items) {
    const p = Promise.resolve().then(() => fn(item));
    ret.push(p);
    if (executing.push(p) >= limit) {
      await Promise.race(executing);
      executing.splice(executing.findIndex(x => x === p), 1);
    }
  }
  return Promise.all(ret);
}
14

エラー処理

try/catch/finally

同期のエラーと(await 付きでは)非同期の拒否を扱うのが、try/catch です。return/throw のときでも、finally が常に動くため — ハンドルを閉じるような後始末に使いましょう。err.code の確認により特定のエラーを捉え、認識しないものをすべて再スローし、予想外のバグが呑み込まれるのでなく表面化するようにしましょう。

nodejs
function parse(str) {
  try {
    return JSON.parse(str);
  } catch (err) {
    console.error('parse failed:', err.message);
    return null;
  } finally {
    console.log('cleanup always runs');
  }
}

// async errors need async catch
async function load() {
  try {
    const data = await fetchData();
    return data;
  } catch (err) {
    if (err.code === 'ENOENT') return defaultData();
    throw err;              // re-throw unknown errors
  }
}

エラーファーストのコールバック

エラーファーストのコールバックでは、err を最初に必ず確認し早く返りましょう — err が設定されているとき data を使ってはいけません。コールバック API をラップするときは、投げるのでなく、自分のコールバックへエラーを転送しましょう(コールバック内の throw は呼び出し元が捉えられません)。投げ得る同期コード(JSON.parse のような)は、try/catch で包みましょう。

nodejs
const fs = require('fs');

// ALWAYS check err first, return early
fs.readFile('missing.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('could not read:', err.message);
    return;            // don't use data
  }
  console.log(data);
});

// propagate the error to your own caller
function readConfig(cb) {
  fs.readFile('config.json', 'utf8', (err, raw) => {
    if (err) return cb(err);
    try { cb(null, JSON.parse(raw)); }
    catch (e) { cb(e); }
  });
}

未捕捉の例外

すべてのハンドラから逃れる同期例外で発火するのが、uncaughtException です — プロセスが今や壊れています。ログに記録し、サーバーを閉じ、exit しましょう(プロセスマネージャーに再起動させます)。忘れられた promise で発火するのが、unhandledRejection です。Node 15 以降、これがプロセスをクラッシュさせるため、.catch() を必ず加えるか、try/catch 内で await しましょう。

nodejs
// last-resort handler for sync exceptions
process.on('uncaughtException', err => {
  console.error('UNCAUGHT:', err);
  // the process is in an unknown state — restart it
  server.close(() => process.exit(1));
});

// rejected promises nobody awaited
process.on('unhandledRejection', (reason, promise) => {
  console.error('UNHANDLED REJECTION:', reason);
});

// Node 15+: unhandled rejections terminate the process
// always add .catch() or wrap in try/await

カスタム Error クラス

構造化されたフィールド(code、field、status)を加え、instanceof によりエラーのタイプを区別するには、Error を継承しましょう。this.name をクラス名へ必ず設定し(古いターゲットでは自動ではありません)、super(message) を呼びましょう。カスタムエラーにより、catch ブロックが読みやすくなります:脆い文字列マッチングの代わりに instanceof で分岐させましょう。

nodejs
// subclass Error to add context
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
    this.code = 'VALIDATION_FAILED';
  }
}

function validate(email) {
  if (!email.includes('@')) {
    throw new ValidationError('email', 'invalid email');
  }
}

// branch on error type with instanceof
try {
  validate('no-at-sign');
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(err.field, err.message);
  } else {
    throw err;
  }
}

Error のプロパティと cause

message、name、stack を持つのが、すべての Error です。安定した機械可読な処理のための code プロパティを加えましょう(Node 自身のエラーが ENOENT、EACCES のようなコードを使います)。基礎のエラーをチェーンするのが、ES2022 の cause オプション(Node 16.9+)です。デバッグのため元のスタックを保ちつつ、低レベルの失敗を包めます。

nodejs
// built-in Error props
const e = new Error('something broke');
e.message;    // 'something broke'
e.stack;      // stack trace string
e.name;       // 'Error'

// add a code for machine-readable handling
const err = new Error('file missing');
err.code = 'ENOENT';
err.errno = -2;

// Error.cause (Node 16.9+) — chain underlying errors
try {
  JSON.parse(bad);
} catch (original) {
  throw new Error('config parse failed', { cause: original });
}

// inspect the cause
console.log(err.cause);            // the original SyntaxError

Domain と後始末

非同期の後始末には(exit を延期できます)「beforeExit」を使い、「exit」は同期の作業だけに使いましょう。exit 前に接続を排水するため、SIGTERM(コンテナのシャットダウン)と SIGINT(Ctrl-C)を扱いましょう — 塞がった接続がプロセスを永遠に縛れないよう、強制終了のタイムアウトを加えましょう。非推奨なのが、Domains です。代わりに、try/catch と非同期のエラー処理を使いましょう。

nodejs
// modern cleanup: 'beforeExit' for async, 'exit' for sync
process.on('beforeExit', async () => {
  await closeDbConnections();
});

process.on('exit', code => {
  // ONLY sync code allowed here — no async, no promises
  console.log('exiting with', code);
});

// graceful signal handling
const shutdown = sig => {
  console.log('got', sig);
  server.close(() => process.exit(0));
  setTimeout(() => process.exit(1), 5000).unref(); // force exit
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
15

デバッグ

console のメソッド

log より多くを console が提供します:オブジェクトの配列を描画するのが table、duration を測るのが time/timeEnd、設定可能な深さ付きでオブジェクトをダンプするのが dir、スタックを表示するのが trace、ヒットを数えるのが count です。本番パイプラインでログとエラーを分離できるよう、console.error(stderr)を使いましょう。

nodejs
console.log('basic');              // stdout
console.error('oops');           // stderr
console.warn('careful');         // stderr

// formatted table
console.table([{ id: 1, n: 'A' }, { id: 2, n: 'B' }]);

// inspect an object in depth
console.dir(obj, { depth: null, colors: true });

// timing a block
console.time('loop');
for (let i = 0; i < 1e6; i++) {}
console.timeEnd('loop');         // loop: 3.2ms

// stack trace
console.trace('where am I');

// count calls
for (let i = 0; i < 3; i++) console.count('hit');

node inspect と DevTools

V8 のインスペクタを始めるのが、--inspect です。そのため、Chrome DevTools(chrome://inspect)や VS Code が接続できます。起動コードが動く前にブレークポイントを設定できるよう、最初の行で止めるのが、--inspect-brk です。ブラウザが利用できない SSH の上で有用なのが、クラシックな「node inspect」のターミナルデバッガです。

nodejs
# open Chrome DevTools debugger
node --inspect app.js
# visit chrome://inspect, click "inspect"

# pause on first line (break before anything runs)
node --inspect-brk app.js

# wait for a debugger client to attach
node --inspect-wait app.js

# the legacy CLI debugger (still works, no browser)
node inspect app.js
# > cont, step, next, breakpoints, repl

debugger ステートメント

デバッガ(DevTools か VS Code)が接続されているときだけ、実行を止めるのが、debugger ステートメントです — さもなければ no-op なので、コードに残しても安全です。起動時に止めるには、--inspect-brk と組み合わせましょう。アドホックな検査のためには、UI のブレークポイントを設定する代わりに、ループや条件の内側へ debugger; を置きましょう。

nodejs
function findBug(arr) {
  let sum = 0;
  for (const n of arr) {
    debugger;        // pauses only when a debugger is attached
    sum += n;
  }
  return sum;
}

// run with --inspect-brk to hit the breakpoint
// node --inspect-brk app.js

// conditional breakpoints in DevTools/VSCode:
//   if (n > 100) { debugger; }

VS Code のデバッグ

VS Code の Node デバッガ(F5)が .vscode/launch.json を読みます。インスペクタを組み込みでプログラムを実行するのが、「request": "launch」で、--inspect 付きで既に始まったプロセスへ接続するのが、「attach」です。ステッピングから Node の内部を隠すのが、skipFiles です。ファイル変更時に自動再起動するのが、「restart」フラグか nodemon です。

nodejs
// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug App",
      "program": "${workspaceFolder}/app.js",
      "skipFiles": ["<node_internals>/**"]
    },
    {
      "type": "node",
      "request": "attach",
      "name": "Attach by PID",
      "processId": "${command:PickProcess}"
    }
  ]
}

// F5 to start; set breakpoints in the editor
// "restart": true, "nodemon" for auto-restart on change

警告とスタックトレース

プロセス警告(メモリリーク、非推奨 API)のスタックを表示するのが、--trace-warnings です。レガシー API の使い方を表面化するのが、--trace-deprecation で、より厳密な CI のためにそれらをハードなエラーへ変えるのが、--throw-deprecation です。ホットな関数を見つけるため、Chrome DevTools で開けるプロファイルを書くのが、--cpu-prof です。より深い非同期トレースのため、Error.stackTraceLimit を上げましょう。

nodejs
# show stack traces for process warnings
node --trace-warnings app.js

# deprecation warnings (use --throw-deprecation to make them errors)
node --trace-deprecation app.js

# capture a stack trace manually
const e = new Error('here');
console.log(e.stack);

# show async stack traces (Node 12+ enabled by default)
Error.stackTraceLimit = 50;   // deeper traces

# profile CPU usage
node --cpu-prof app.js        # writes CPU.*.cpuprofile
# then load the file in Chrome DevTools
16

Crypto

ハッシュ化(createHash)

一方向のダイジェストを作るのが、createHash です。チェックサムと署名のモダンなデフォルトが、SHA-256 で、セキュリティのため MD5/SHA-1 を避けましょう(衝突しやすいです)。データを漸進的に供給でき、バッファリングせず大きなファイルをストリーミングできます。hex 文字列を返すのが、digest('hex') で、「base64」も一般的です。ハッシュ化はパスワードの保存では「ありません」 — pbkdf2/scrypt を使いましょう。

nodejs
const crypto = require('crypto');

// common hashes: sha256, sha512, md5 (insecure!), sha1
const hash = crypto.createHash('sha256');
hash.update('hello');
hash.update(' world');        // can chain updates
console.log(hash.digest('hex'));
// b94d...  (64 hex chars)

// one-shot hashing
const h = crypto.createHash('sha256').update('data').digest('hex');
console.log(h);

// file hash (streaming)
const fs = require('fs');
const fhash = crypto.createHash('sha256');
fs.createReadStream('big.iso').on('data', c => fhash.update(c))
  .on('end', () => console.log(fhash.digest('hex')));

HMAC(createHmac)

共有シークレットでデータに署名し、受信者が整合性と真正性の両方を検証できるようにするのが、HMAC です。JWT の署名と Webhook の検証(GitHub、Stripe)の基礎です。署名の比較には必ず timingSafeEqual を使いましょう — 通常の === が、攻撃者が悪用できるタイミングの違い経由で情報を漏らします。

nodejs
const crypto = require('crypto');

// HMAC = keyed hash (authenticity + integrity)
const secret = process.env.SECRET_KEY;
const hmac = crypto.createHmac('sha256', secret);
hmac.update('payload to sign');
const signature = hmac.digest('hex');

// verify a webhook signature (constant-time compare)
function verify(payload, receivedSig) {
  const expected = crypto.createHmac('sha256', secret)
    .update(payload).digest('hex');
  // timingSafeEqual prevents timing attacks
  return crypto.timingSafeEqual(
    Buffer.from(expected),
    Buffer.from(receivedSig)
  );
}

ランダムバイト

暗号学的に安全なランダムデータを作るのが、crypto.randomBytes です — トークン、ID、シークレットに使いましょう。多くのバイトを生成するとき、イベントループのブロックを避けるのが、非同期形式です。偏りのないランダム整数を与えるのが、crypto.randomInt で、RFC-4122 v4 の UUID を生成するのが、randomUUID() です。セキュリティに関わるものに Math.random() を使ってはいけません。

nodejs
const crypto = require('crypto');

// async (preferred — doesn't block the event loop)
crypto.randomBytes(16, (err, buf) => {
  const token = buf.toString('hex');   // 32-char hex
});

// sync (blocks; fine for small sizes)
const id = crypto.randomBytes(8).toString('hex');

// random integer in [min, max)
const n = crypto.randomInt(1, 101);     // 1..100

// random UUID (Node 14.17+)
const uuid = crypto.randomUUID();
// '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

// use crypto, NEVER Math.random() for secrets!

暗号化(createCipheriv)

推奨される対称暗号が、AES-256-GCM です — 認証されているため、改ざんが検出されます。与えられた鍵で暗号化ごとに IV(nonce)が一意でなければならず(再利用してはいけません)、暗号文と共に保存しましょう。復号時に整合性を検証するのが、setAuthTag です。非推奨の createCipher を(鍵を安全でなく導出するため)使ってはいけません — 適切な鍵付きの createCipheriv を必ず使いましょう。

nodejs
const crypto = require('crypto');
const algorithm = 'aes-256-gcm';

// AES-256-GCM (authenticated encryption) ----------------
const key = crypto.randomBytes(32);   // 256-bit key
const iv = crypto.randomBytes(12);    // 96-bit nonce

function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  const enc = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
  const tag = cipher.getAuthTag();    // GCM auth tag
  return { enc, tag };
}

function decrypt(enc, tag) {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  decipher.setAuthTag(tag);           // verify integrity
  return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
}

パスワードのハッシュ化(pbkdf2、scrypt)

遅く塩漬けされた KDF でパスワードをハッシュしましょう — 素のハッシュでは決してありません。Node に組み込まれているのが、pbkdf2(ハードウェアが改善するにつれ反復を上げ調整する)と、scrypt(メモリが重く、GPU 耐性があります)です。検証し後にパラメータをアップグレードできるよう、反復、ソルト、ハッシュを一緒に保存しましょう。タイミング情報を漏らさずハッシュを確認するのが、timingSafeEqual です。

nodejs
const crypto = require('crypto');

// PBKDF2: tuned with iterations
function hashPbkdf2(password) {
  const salt = crypto.randomBytes(16);
  const iterations = 100000;
  const hash = crypto.pbkdf2Sync(password, salt, iterations, 64, 'sha256');
  return `${iterations}.${salt.toString('hex')}.${hash.toString('hex')}`;
}

// scrypt: memory-hard, resistant to GPU/ASIC attacks
function hashScrypt(password) {
  const salt = crypto.randomBytes(16);
  const hash = crypto.scryptSync(password, salt, 64, { N: 16384 });
  return salt.toString('hex') + '.' + hash.toString('hex');
}

// verify: re-hash with the same salt and compare
function verify(password, stored) {
  const [iter, salt, hash] = stored.split('.');
  const computed = crypto.pbkdf2Sync(password, Buffer.from(salt, 'hex'),
    +iter, 64, 'sha256');
  return crypto.timingSafeEqual(Buffer.from(hash, 'hex'), computed);
}

タイミングセーフな比較

一定時間で 2 つのバッファを比較し、攻撃者がレスポンスの遅延からバイトごとにシークレットを推測するタイミング攻撃を防ぐのが、timingSafeEqual です。両方のバッファが同じ長さでなければなりません(先に確認しますが、その長さの確認自体が長さを漏らし得ます — シークレットのためには、両側を先にハッシュしましょう)。トークン、署名、API キーを比較するときはいつでも使いましょう。

nodejs
const crypto = require('crypto');

// NORMAL compare leaks via timing (returns early on first diff)
// 'secret' === userInput  // BAD for secrets

// timingSafeEqual takes equal-length Buffers
function safeEqual(a, b) {
  const bufA = Buffer.from(a);
  const bufB = Buffer.from(b);
  if (bufA.length !== bufB.length) return false;
  return crypto.timingSafeEqual(bufA, bufB);
}

// common use: API key check
function auth(req) {
  const provided = req.headers['x-api-key'] || '';
  return safeEqual(provided, process.env.API_KEY);
}
17

OS モジュール

システム情報

ホスト環境を公開するのが、os です。移植性のチェックのための OS の識別が、platform/arch/type です。プラットフォームの行末シーケンスを与えるのが、os.EOL で — プラットフォームが正しいテキストファイルを書くとき使いましょう。マシンのネットワーク名が、hostname で、どのインスタンスがリクエストを処理したかのロギングに有用です。

nodejs
const os = require('os');

os.platform();    // 'linux', 'darwin', 'win32'
os.arch();        // 'x64', 'arm64'
os.type();        // 'Linux', 'Darwin', 'Windows_NT'
os.release();     // kernel version
os.hostname();    // machine hostname
os.uptime();      // seconds since boot
os.EOL;           // '\n' (POSIX) or '\r\n' (Windows)

// detect platform portably
const isWin = os.platform() === 'win32';
const isMac = os.platform() === 'darwin';

CPU 情報

(ハイパースレッドを含む)論理コアの配列を返すのが、os.cpus() です。そのため、その長さが cluster.fork のための正しい同時実行のヒントです。model、speed、times(user/sys/idle)を各エントリが持ちます。システム負荷を報告するのが、loadavg です(Linux/macOS のみ)— cpus().length を超える値が飽和を示唆します。

nodejs
const os = require('os');

// logical core count (threads, not physical)
os.cpus().length;        // 8

// detailed per-core info
os.cpus().forEach((cpu, i) => {
  console.log(`core ${i}: ${cpu.model} @ ${cpu.speed}MHz`);
});

// 1/5/15-minute load averages (NOT on Windows)
os.loadavg();            // [0.45, 0.32, 0.28]

// set process scheduling priority
os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);

メモリ

システム RAM を報告するのが、os.totalmem/freemem で、このプロセスのフットプリントを報告するのが、process.memoryUsage です。OS レベルのメモリが rss で、生きている JS のオブジェクトが、heapUsed です。リークのため heapUsed を見ましょう。バイトを MB へ変換するには、1024*1024(1048576)で割りましょう。heap が上限近くまで成長したら、--max-old-space-size を調整しましょう。

nodejs
const os = require('os');

// system memory (bytes)
os.totalmem();          // e.g. 17179869184
os.freemem();           // currently free bytes

// process memory usage (bytes)
const m = process.memoryUsage();
m.rss;          // resident set size (total RAM held)
m.heapTotal;    // V8 heap allocated
m.heapUsed;     // V8 heap actually used
m.external;     // C++ objects bound to JS
m.arrayBuffers; // memory in ArrayBuffers

// human-readable
console.log(`heap: ${(m.heapUsed / 1048576).toFixed(1)} MB`);

ネットワークインターフェース

アドレス、MAC、ファミリー(IPv4/IPv6)と共に、各ネットワークインターフェースを一覧するのが、os.networkInterfaces() です。ループバックを印付けるのが、「internal」のフラグです。サーバーの bind やロギングのために、マシンの LAN IP を発見する移植可能な方法です。複数のアドレスを各インターフェースが持ち得ます(マルチホームのホスト)。

nodejs
const os = require('os');

const nets = os.networkInterfaces();
for (const name of Object.keys(nets)) {
  for (const net of nets[name]) {
    console.log(`${name} ${net.family}: ${net.address} (${net.mac})`);
  }
}
// en0 IPv4: 192.168.1.10 (aa:bb:cc:...)
// lo IPv4: 127.0.0.1 (:::...)

// find this machine's LAN IPv4
function getLanIp() {
  for (const nets of Object.values(os.networkInterfaces())) {
    for (const n of nets) {
      if (n.family === 'IPv4' && !n.internal) return n.address;
    }
  }
  return '127.0.0.1';
}

ユーザーとパス

ユーザーのホームディレクトリを返すのが、os.homedir で、システムの一時フォルダを返すのが、os.tmpdir です — どちらもプラットフォームを意識するため、ハードコードされたパスよりこれらを推奨しましょう。現在のユーザーの身元を与えるのが、os.userInfo です。SIGTERM のための 15 のようなマジックナンバーをハードコードしないため、数値のシグナル/errno/優先度の値を一元化するのが、os.constants です。

nodejs
const os = require('os');

os.homedir();      // /home/alice  or C:\Users\alice
os.tmpdir();       // /tmp         or C:\Users\...\Temp
os.userInfo();     // { username, uid, gid, homedir, shell }
os.constants;      // signal/errno/priority constants

// errno constants map
os.constants.errno.ENOENT;   // -2
// signal constants
os.constants.signals.SIGTERM; // 15

// priority constants
os.constants.priority.PRIORITY_HIGH;

// build a portable temp path
const path = require('path');
const tmpFile = path.join(os.tmpdir(), 'app-' + Date.now() + '.log');
18

Process

process.argv

コマンドラインの引数を保持するのが、process.argv です:node のバイナリが argv[0]、スクリプトが argv[1]、残りがユーザーの引数です。ユーザーの引数だけを得るには、最初の 2 つを slice しましょう。おもちゃのスクリプトを超えるものには、minimist、yargs、commander のようなパーサを使いましょう — フラグ、型、デフォルト、ヘルプテキストを扱ってくれます。

nodejs
// argv[0] = node path, argv[1] = script path, argv[2+] = args
// node app.js --port 3000 users.csv
console.log(process.argv);
// ['/usr/bin/node', '/app/app.js', '--port', '3000', 'users.csv']

const args = process.argv.slice(2);
console.log(args);  // ['--port', '3000', 'users.csv']

// minimal flag parsing
function parseArgs(arr) {
  const out = { _: [] };
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].startsWith('--')) out[arr[i].slice(2)] = arr[++i];
    else out._.push(arr[i]);
  }
  return out;
}
// for real CLI use commander, yargs, or minimist

process.env

文字列として環境変数を保持するのが、process.env です。慣例により、PORT、NODE_ENV、DATABASE_URL、API_KEY が env から来るため、同じコードが環境をまたいで動きます。開発で .env ファイルをロードするには、dotenv パッケージを使いましょう。シークレットをコミットしてはいけません — ホスト/CI の環境経由で注入しましょう。

nodejs
// read environment variables
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV || 'development';

const isProd = process.env.NODE_ENV === 'production';

// set an env var (affects child processes too)
process.env.MY_VAR = 'value';

// load .env files (install: npm i dotenv)
// require('dotenv').config();

// enumerate everything
for (const [k, v] of Object.entries(process.env)) {
  console.log(k, '=', v);
}

process.exit と終了コード

I/O バッファが流れる前にさえ、即座に終了するのが、process.exit(n) です — process.exitCode を設定しイベントループに自然に排水させる方を推奨しましょう。成功を意味するのが、exit 0 で、シェルと CI への失敗の合図が、非ゼロです。シグナル N による終了を符号化するのが、慣例の 128+N です(そのため SIGTERM が 143 を出します)。

nodejs
// exit immediately with a status code
process.exit(0);    // success
process.exit(1);    // general failure

// exit code is also settable
process.exitCode = 2;   // used if the loop ends naturally

// prefer setting exitCode + returning over process.exit()
// so async work can finish

// common conventions:
// 0  success
// 1  general error
// 2  misuse (bad args)
// 124 timeout (from the 'timeout' command)
// 128+N  killed by signal N (e.g. 143 = SIGTERM)

stdin / stdout / stderr

書き込み可能なストリームであるのが、process.stdout と process.stderr です — (console.log と違い)write() が改行を加えません。'data' イベントか非同期反復(最もきれいなモダンパターン)で消費できる readable ストリームが、stdin です。パイプの中で本物の出力から分離できるよう、診断には stderr を使いましょう。

nodejs
// stdout/stderr are writable streams
process.stdout.write('no newline');
process.stdout.write('line\n');
console.log === process.stdout.write.bind(...); // roughly

// stdin is a readable stream
process.stdin.setEncoding('utf8');
process.stdin.on('data', chunk => console.log('got:', chunk));

// read all of stdin (async iteration)
async function readStdin() {
  let data = '';
  for await (const chunk of process.stdin) data += chunk;
  return data;
}

// ask a yes/no question
process.stdin.resume();
process.stdin.once('data', input => process.exit(input[0] === 'y'.charCodeAt(0) ? 0 : 1));

プロセスのイベント(シグナル)

イベントループが空になった後に発火するのが、「exit」です — そこで動くのは同期コードだけです。非同期の作業ができ、exit を延期し得るのが、「beforeExit」です。サーバーと DB 接続を優雅に閉じるため、SIGINT(Ctrl-C)と SIGTERM(docker stop、kill)を扱いましょう。塞がった接続がプロセスを永遠に捕らえられないよう、必ず強制終了のタイムアウトを設定しましょう。

nodejs
// lifecycle events
process.on('exit', code => {
  // sync only here — no async, no event loop
  console.log('bye, code', code);
});
process.on('beforeExit', () => {
  // async OK; can postpone exit
});

// signal handlers (Unix + Windows for SIGINT/SIGTERM)
process.on('SIGINT', () => {       // Ctrl-C
  console.log('graceful shutdown...');
  server.close(() => process.exit(0));
});
process.on('SIGTERM', () => {      // kill / docker stop
  server.close(() => process.exit(0));
});
process.on('SIGHUP', () => reloadConfig());

memoryUsage と uptime

身元(pid、ppid、platform、version)とランタイムの統計(uptime、memoryUsage、cpuUsage)を公開するのが、process です。作業ディレクトリが cwd() で、それを変え、相対パスの解決に影響するのが、chdir です。ヘルスチェックのエンドポイントとオートスケーリングの指標の基礎が、memoryUsage と cpuUsage です。

nodejs
// process info
process.pid;             // OS process ID
process.ppid;            // parent PID
process.platform;        // 'linux', 'darwin', 'win32'
process.version;         // 'v20.11.0'
process.versions;        // { v8, openssl, modules, ... }
process.cwd();           // current working directory
process.uptime();        // seconds since process started

// change directory
process.chdir('/tmp');

// memory snapshot
const m = process.memoryUsage();
console.log(m.rss, m.heapUsed);

// CPU usage of this process
const cpu = process.cpuUsage();
console.log(cpu.user, cpu.system);  // microseconds
19

ネットワーク(net)

TCP サーバー

生の TCP サーバーを作るのが、net.createServer です。Socket(Duplex ストリーム)付きでコールバックを呼ぶのが、各接続です。'data' イベントで読み、socket.write で書きましょう。プロセスがクラッシュするため、ソケット上の「error」は必ず扱いましょう。HTTP の下の基盤が TCP です — カスタムプロトコル、ゲーム、プロキシに有用です。

nodejs
const net = require('net');

const server = net.createServer(socket => {
  console.log('client connected', socket.remoteAddress);
  socket.write('welcome\n');

  socket.on('data', data => {
    socket.write('echo: ' + data);     // echo back
  });

  socket.on('end', () => console.log('client left'));
  socket.on('error', err => console.error('socket err', err));
});

server.listen(5000, () => {
  console.log('TCP server on port 5000');
});

// test with: nc localhost 5000  or  telnet localhost 5000

TCP クライアント

TCP クライアントのソケットを開くのが、net.connect(createConnection の別名)です。接続時にコールバックが発火し、入ってくるバイトを届けるのが「data」イベントです。Buffer でなく文字列を受け取るため、エンコーディングを設定しましょう。どのストリームと同様、クラッシュを避けるため「error」を扱いましょう。「end」でソケットが自動的に閉じ、自分の側を半分閉じるのが、client.end() です。

nodejs
const net = require('net');

// connect to a TCP server
const client = net.connect(5000, 'localhost', () => {
  console.log('connected');
  client.write('hello server\n');
});

client.setEncoding('utf8');
client.on('data', data => console.log('server said:', data));
client.on('end', () => console.log('disconnected'));
client.on('error', err => console.error(err));

// or with an options object + timeout
const c = net.createConnection({
  port: 5000,
  host: 'localhost',
  timeout: 5000
});

Socket のイベントとデータ

メッセージプロトコルでなくバイトストリームであるのが、TCP です — 1 つの「data」イベントが 1 メッセージと等しくならず、データが分割・合体し得ます。自分でメッセージをフレーム化 MUST です(長さの接頭辞、区切り、パーサ)。死んだ相手の検出が setKeepAlive で、アイドル接続の切断が setTimeout、書き込みバッファが空になった合図が「drain」です。

nodejs
const net = require('net');

net.createServer(socket => {
  socket.setEncoding('utf8');
  socket.setKeepAlive(true, 30000);   // enable TCP keepalive
  socket.setTimeout(60000);           // idle timeout

  socket.on('data', chunk => {
    // TCP is a STREAM: chunks may split or merge messages.
    // Frame your protocol (length prefix, delimiter, etc.)
    console.log('received', chunk.length, 'bytes');
  });

  socket.on('timeout', () => socket.end());
  socket.on('close', hadError => console.log('closed', hadError));
  socket.on('drain', () => console.log('buffer drained'));
}).listen(5000);

書き込みと半分閉じ

backpressure を尊重するのが、socket.write です(満杯のとき false を返す — 「drain」を待ちましょう)。pending の書き込みを流し、まだ相手を読みながら FIN を送るのが、end() の半分閉じです。ソケットを即座に殺すのが、destroy() です。ロギングとアクセス制御のための remoteAddress/remotePort を使いましょう。速い送り手を絞るのが、pause/resume です。

nodejs
const net = require('net');

net.createServer(socket => {
  // write() returns false when the buffer is full (backpressure)
  const ok = socket.write(bigPayload);
  if (!ok) socket.once('drain', writeMore);

  // half-close: send FIN, keep reading
  socket.end();   // writes any pending data, then closes our side
  // socket.end('final message\n'); // write + close

  // fully destroy the socket immediately
  socket.destroy();

  // pause/resume reading
  socket.pause();
  socket.resume();

  // address info
  socket.remoteAddress;  // '192.168.1.5'
  socket.remotePort;     // 54321
}).listen(5000);

サーバーのイベントと IPC

「connection」(クライアントごと)、「listening」、「error」(EADDRINUSE を扱う)、「close」を出すのが、net.Server です。Unix ソケット(Windows では名前付きパイプ)のためのパスを listen が受け付けられ — 同じホスト上のプロセス間の、速く安全なローカル IPC です。新しい接続の受け付けを止め、既存のものが終わるのを待つのが、server.close() です。

nodejs
const net = require('net');

const server = net.createServer();
server.on('connection', socket => {});   // same as createServer cb
server.on('listening', () => console.log('bound'));
server.on('error', err => {
  if (err.code === 'EADDRINUSE') console.error('port taken');
});
server.on('close', () => console.log('server closed'));

server.listen(5000);

// Unix domain socket / named pipe (fast local IPC)
server.listen('/tmp/app.sock');
// Windows: server.listen('\\\\.\\pipe\\app');

// stop accepting, close idle connections
server.close(() => console.log('all done'));

// get bound address
server.address();   // { port: 5000, family: 'IPv4', address: '::' }
20

タイマーとユーティリティ

タイマー(setTimeout、setInterval)

遅延の後に 1 回動くのが、setTimeout で、繰り返すのが、setInterval です。同じループのターンで I/O イベントの後に動くのが、setImmediate です。さらに早く、現在の操作の直後に動くのが、queueMicrotask です。ループ内の順序:microtasks が最初で、次に timers、次に I/O、次に setImmediate です — 後続の作業のスケジューリング時に知っておくと有用です。

nodejs
// run once after a delay (ms)
const t = setTimeout(() => console.log('hi'), 1000);

// run repeatedly every interval
const i = setInterval(() => console.log('tick'), 2000);

// run right after the current event loop turn
setImmediate(() => console.log('immediate'));

// run before the next event loop turn (microtask)
queueMicrotask(() => console.log('microtask'));

// order inside one loop:
// microtasks -> timers -> I/O -> check (setImmediate)

タイマーのクリアと ref

一致する clear 関数を各タイマーが持ちます。プロセスを生かさないと印付けるのが、unref() です — unref'd されたタイマーだけが残れば、Node が exit します(プロセスを縛るべきでない定期的な後始末に便利です)。逆にするのが、ref() です。遅延の後の余分な引数がコールバックへ転送されるため、余分な矢印関数が避けられます。

nodejs
const t = setTimeout(() => {}, 1000);
clearTimeout(t);     // cancel

const i = setInterval(() => {}, 1000);
clearInterval(i);

const imm = setImmediate(() => {});
clearImmediate(imm);

// keep the event loop alive?
// timers do by default; unref() lets the process exit if
// only this timer is pending
const timer = setInterval(() => {}, 1000);
timer.unref();       // won't keep Node alive
timer.ref();         // keep alive again

// pass args to the callback
setTimeout((a, b) => console.log(a, b), 500, 'x', 'y');

util.inspect と format

printf 風のプレースホルダー(%s %d %j %o %O %%)で文字列を組み立てるのが、util.format です。任意のオブジェクトを描画するのが、util.inspect で — 完全な色付きのダンプのためには { depth: null, colors: true } を渡し、ログに有用です。呼び出されたとき DeprecationWarning を出す(--trace-deprecation で表面化される)関数を包むのが、util.deprecate です。

nodejs
const util = require('util');

// format like printf
util.format('%s:%d', 'port', 3000);   // 'port:3000'
util.format('%j', { a: 1 });           // JSON

// deep inspect an object (what console.dir uses)
util.inspect(obj, { depth: null, colors: true, compact: false });

// pretty-print a function (its source)
util.inspect(function f() { return 1; });

// deprecate an API with a warning
const oldFn = util.deprecate(
  () => doThingOldWay(),
  'oldFn() is deprecated, use newFn() instead'
);

util.promisify

エラーファーストのコールバック関数を、Promise を返すものへ包むのが、util.promisify です — レガシーなコールバック API から async/await への橋渡しです。ネイティブの promise 版を今や ship するのが、多くのコアモジュール(fs/promises)で、これらの方が好ましいですが、promisify が依然サードパーティのコールバック API を救います。変換を制御するため、関数が [util.promisify.custom] を定義できます。

nodejs
const util = require('util');
const fs = require('fs');

// turn an error-first callback fn into a promise fn
const readFile = util.promisify(fs.readFile);
const text = await readFile('data.txt', 'utf8');

// works on custom functions too
function delay(ms, cb) { setTimeout(() => cb(null, ms), ms); }
const delayP = util.promisify(delay);
await delayP(100);

// custom promisify symbol (controls the promise behavior)
// const { promisify } = util;
// obj[util.promisify.custom] = () => Promise.resolve(42);

// many core modules ship promise versions directly:
// require('fs/promises'), require('dns/promises')

util types と callbackify

instanceof よりクロスレルムとサブクラスの端のケースをよく生き延びる、信頼できるタイプのチェックを提供するのが、util.types です(isPromise、isAsyncFunction、isRegExp、isMap)。promisify の逆が、util.callbackify で — promise ベースの関数をコールバックスタイルの API へ公開しなければならないときに有用です。MIME タイプをパースし操作するのが、util.MIMEType(Node 19+)です。

nodejs
const util = require('util');

// type checks
util.isPromise(Promise.resolve());    // true
util.isFunction(() => {});            // true
util.types.isMap(new Map());          // true
util.types.isAsyncFunction(async () => {}); // true
util.types.isRegExp(/x/);             // true

// reverse of promisify: promise -> error-first callback
const readFileCb = util.callbackify(require('fs/promises').readFile);
readFileCb('x.txt', 'utf8', (err, data) => {
  if (err) console.error(err);
  else console.log(data);
});

// MIME type utilities (Node 19+)
util.MIMEType.parse('text/html; charset=utf-8');

nextTick 対 setImmediate

現在の同期操作の直後、I/O の「前に」動くのが、process.nextTick です。そのため、nextTick を再帰的に呼ぶと、I/O が無期限に飢えます(ループが決して進みません)。I/O の後、「check」フェーズで動くのが、setImmediate です。イベントループに譲り pending の I/O を確定させるには、setImmediate を推奨し、任意の I/O コールバックの前に起きなければならない後始末には、nextTick を取っておきましょう。

nodejs
// process.nextTick: runs BEFORE I/O, after the current op
process.nextTick(() => console.log('tick'));

// setImmediate: runs AFTER I/O events, in the 'check' phase
setImmediate(() => console.log('immediate'));

// setTimeout(0): runs in the timers phase, after nextTick
setTimeout(() => console.log('timeout'), 0);

// typical order in one loop turn:
// 1. current sync code
// 2. nextTick callbacks  (can starve I/O!)
// 3. timers
// 4. I/O callbacks
// 5. setImmediate

// prefer setImmediate to yield to I/O; use nextTick for
// immediate post-sync cleanup

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.