はじめに
REPL とスクリプトの実行
Node.js のコードで実験するための対話シェルが、REPL(Read-Eval-Print Loop)です。開発中の自動再起動には node --watch を使いましょう。ES モジュールには、package.json の type:module か .mjs 拡張子が必要です。
# 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 です。
# 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.jspackage.json とプロジェクトの初期化
package.json を作るのが、npm init です。デフォルトのモジュールシステムを決めるのが、"type" フィールドです:.js ファイルで ES モジュール構文を有効化するのが "module"、require/module.exports を保つのが "commonjs"(デフォルト)です。パッケージが require されたときのエントリポイントが、"main" です。
# 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" フィールドです。
# 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 のように)。
# 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 ツールが使い、グローバルインストールでコマンドが公開されます。
#!/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" }
}モジュールシステム
CommonJS の require と exports
CommonJS のモジュールを同期的にロードし、その module.exports を返すのが、require() です。require が解決するのは、相対パス(./、../)、組み込み(fs)、node_modules です。エクスポート全体を置き換えるときは、exports ではなく module.exports へ必ず代入しましょう — exports は当初、module.exports の別名にすぎないためです。
// 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)); // 12ES Modules の import/export
静的な import/export を使うのが、ES Modules です — 束縛がライブで、巻き上げられます。任意の名前でインポートされるのが、デフォルトエクスポートです(波括弧なし)。一致する名前の波括弧を必要とするのが、名前付きエクスポートです。名前空間オブジェクトを作るのが、import * as です。設計上非同期でありモダンな標準が、ESM です。
// 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 を返し、遅延ローディングと条件付きインポートを可能にします — 起動時間の削減や省略可能な機能のロードに最適です。サーバーでのコード分割にも使いましょう。
// 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')(./ なし)です。
// 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 を。
// 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 です。
// 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.mjsnpm と pnpm
npm init と package.json
package.json をスキャフォールドするのが、npm init です。デフォルト付きでプロンプトをスキップするのが、-y です。今後の init のために ~/.npmrc へ設定を保存するのが、npm set です。組織やレジストリでの名前衝突の回避に有用なのが、スコープ付きパッケージ(@org/name)です。
# 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 です。
# 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 pm2npm スクリプト
npm run <name> 経由で実行されるのが、package.json のスクリプトです。特別なのが、start と test です(npm start / npm test)。自動的に実行されるのが、pre/post のフック(pretest、postbuild)です。基礎のコマンドへ引数を転送するには、-- を使いましょう。カスタムスクリプトのため「run」という単語をスキップできるのが、pnpm です。
// 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 productionnpx と pnpm dlx
グローバルインストールなしでパッケージのバイナリを実行するのが、npx です — ダウンロードし、実行し、破棄します。スキャフォルダ(create-vite)やローカルの node_modules/.bin のツールの実行に完璧です。インストール確認のスキップが、--yes です。pnpm 版が、pnpm dlx です。
# 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 を使いましょう。
# 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 を推奨しましょう。
# 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]ファイルシステム(fs)
ファイルの読み取り
fs が提供するのは、sync(readFileSync)、コールバック(readFile)、promise(fs/promises の readFile)の API です。イベントループをブロックするのが sync 呼び出しであるため、サーバーでは避けましょう。async/await のモダンな選択が、fs/promises です。エンコーディングなしでは、readFile が Buffer を返します。
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 を推奨します。
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+)。
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 ですが、プラットフォーム間で一貫しないことがあります。
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 で包みましょう。
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 です。
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);パスの処理
path.join と path.resolve
プラットフォームの区切りを使いセグメントを連結し、結果を正規化するのが、path.join です。process.cwd() から始まる絶対パスを作るのが、path.resolve で、絶対のセグメントが前のセグメントを破棄します。Windows と POSIX でパスが機能するよう、文字列連結の代わりに必ず path.join を使いましょう。
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 portabilitydirname、basename、extname
ディレクトリを返すのが dirname で、(省略可能に拡張子を剥ぎ取る)ファイル名を返すのが basename、最後の拡張子(ドットを含む)を返すのが extname です。.tar.gz のような複数パートの拡張子には、最後の .gz だけが返されます。これらは純粋な文字列操作で — ファイルシステムへのアクセスはありません。
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 namepath.parse と format
パスを root、dir、base、name、ext へ分割するのが、path.parse で、再構成するのが、path.format です。あるディレクトリから別のディレクトリへ行くのに必要な相対パスを計算するのが、path.relative です。一緒に、面倒な文字列のスライシングでなく宣言的なパス操作ができます。
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 を使いましょう。
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:\\'); // trueFile URL と pathToFileURL
file:// URL で識別されるのが、ES Modules です。通常のパスを動的な import() のための URL へ変えるのが、url.pathToFileURL で、逆方向が url.fileURLToPath です。ESM では、import.meta.url が既に file URL であるため — __filename を複製するには、fileURLToPath でパスへ変換しましょう。