Node.js 学習ノート

バックエンド開発・非同期処理・Linux サーバー運用の個人的な技術メモ

1. Promise.allSettled を使った安全な並列非同期処理

2026-11-22Node.js

複数の外部 API を並列で呼び出す際、Promise.all は 1 件でも失敗すると全体が reject されます。部分的な失敗を許容して処理を継続したい場合は Promise.allSettled を使うのが安全です。

const tasks = urls.map(url => fetch(url).then(r => r.json()));
const results = await Promise.allSettled(tasks);

const succeeded = results
  .filter(r => r.status === 'fulfilled')
  .map(r => r.value);

2. PM2 による Node.js プロセス永続化とメモリ上限設定

2026-11-18運用・監視

長時間稼働する Node.js サービスでは、意図しないメモリリークによる OOM Killer 回避が重要です。ecosystem.config.js に max_memory_restart を定義しておくと、閾値超過時に自動で安全に再起動されます。

module.exports = {
  apps: [{
    name: "api-worker",
    script: "./src/index.js",
    max_memory_restart: "512M",
    env: { NODE_ENV: "production" }
  }]
};

3. Nginx リバースプロキシにおける Keep-Alive とタイムアウト調整

2026-11-12Linux / Nginx

Nginx からローカルの Node.js バックエンドへプロキシする場合、デフォルトでは HTTP/1.0 が使われるため、明示的に proxy_http_version 1.1 と空の Connection ヘッダを指定してコネクションを再利用します。

location /api/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_read_timeout 120s;
}

4. Stream と pipeline で大容量ログファイルを省メモリ処理する

2026-11-05Node.js

数百 MB のファイルを fs.readFile で一括読み込みするとヒープメモリを圧迫します。node:stream/promises の pipeline を使えば、エラーハンドリングも含めて簡潔にチャンク単位で処理できます。

import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';

await pipeline(
  createReadStream('./access.log'),
  createGzip(),
  createWriteStream('./access.log.gz')
);

5. journalctl を使った systemd サービスのログ確認と容量制限

2026-10-28Linux / Nginx

Ubuntu サーバーを長期運用していると systemd のジャーナルログがディスクを圧迫することがあります。直近のエラー確認とディスク使用量の上限設定をメモしておきます。

# 特定サービスの直近 50 行を表示
journalctl -u nginx.service -n 50 --no-pager

# ログの最大容量を 200MB に制限
journalctl --vacuum-size=200M

6. AbortController を使った fetch リクエストのタイムアウト実装

2026-10-21Node.js

Node.js 標準の fetch にはデフォルトでタイムアウトがありません。応答しない外部サーバーで処理が詰まるのを防ぐため、AbortSignal.timeout() を組み合わせて上限時間を指定します。

try {
  const res = await fetch('https://example.jp/health', {
    signal: AbortSignal.timeout(5000)
  });
  console.log(res.status);
} catch (err) {
  if (err.name === 'TimeoutError') console.error('Request timed out');
}

7. Node.js サーバーの Graceful Shutdown(安全な終了処理)

2026-10-15運用・監視

デプロイや再起動時に処理中のリクエストを強制切断しないよう、SIGTERM や SIGINT を捕捉して新規受付を停止し、既存コネクションの完了を待ってからプロセスを終了させます。

function shutdown() {
  server.close(() => {
    console.log('HTTP server closed cleanly.');
    process.exit(0);
  });
  setTimeout(() => process.exit(1), 10000);
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

8. crontab の代わりに systemd タイマーで定期バッチを管理する

2026-10-08Linux / Nginx

systemd-timer を使うと実行ログが自動的に journald へ記録され、前回の実行状況や次回の予定時刻も一覧で確認できるため、サーバー運用の保守性が上がります。

# 登録済みのタイマー一覧と次回実行時刻を確認
systemctl list-timers --all

# タイマー単位のログを確認
journalctl -u backup-task.service --since today

9. EventEmitter によるモジュール間の疎結合なイベント通知

2026-10-02Node.js

監視モジュールと通知モジュールを直接インポートし合うと依存関係が複雑になります。Node.js 標準の EventEmitter を仲介させることで、機能追加やテストがしやすくなります。

import { EventEmitter } from 'node:events';
const bus = new EventEmitter();

bus.on('alert', (msg) => console.warn('[ALERT]', msg));
bus.emit('alert', 'Memory usage exceeded 80%');

10. ss と free コマンドによる Linux サーバー簡易リソース診断

2026-09-25運用・監視

アプリの応答が遅いと感じたときにまず確認する基本コマンドの備忘録です。ソケット接続数と実メモリの空き容量を素早くチェックできます。

# 待機中ポートとプロセス一覧を確認
ss -tulpn

# メモリおよびスワップの使用量を MB 単位で表示
free -m