Skip to content

Node.js 치트시트

서버 측 개발을 위한 Chrome V8 엔진 기반 JavaScript 런타임입니다.

01

시작하기

REPL과 스크립트 실행

REPL(Read-Eval-Print Loop)은 Node.js 코드를 실험하는 인터랙티브 셸입니다. 개발 자동 재시작에는 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는 런타임 경고의 스택 트레이스를 보여 주고, NODE_OPTIONS는 CLI 플래그를 담는 단일 환경 변수로 컨테이너나 npm 스크립트 안에서 편리합니다. --inspect는 Chrome DevTools 디버거를 엽니다.

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과 프로젝트 초기화

npm init이 package.json을 만듭니다. "type" 필드가 기본 모듈 시스템을 결정합니다. "module"은 .js 파일에서 ES 모듈 문법을, "commonjs"(기본)는 require/module.exports를 유지합니다. "main"은 패키지가 require될 때의 진입점입니다.

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 vs ES Modules

Node는 두 모듈 시스템을 지원합니다. 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는 process, console, Buffer, 타이머 같은 전역을 임포트 없이 제공합니다. __dirname과 __filename은 CommonJS 전용이며, 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)

shebang 줄(#!/usr/bin/env node)이 있으면 파일이 Unix에서 독립 명령으로 실행됩니다. 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

require()는 CommonJS 모듈을 동기 로드하고 그 module.exports를 반환합니다. 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

ES Modules는 정적 import/export를 씁니다. 바인딩은 live이며 호이스팅됩니다. default export는 어떤 이름으로든(중괄호 없이) 임포트되고, named export는 이름이 일치하는 중괄호가 필요합니다. 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()

import()는 CJS와 ESM 모두에서 쓸 수 있는 동적·비동기 임포트입니다. 모듈 네임스페이스로 resolve되는 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 불필요. 대부분 콜백 API를 노출하며 많은 모듈이 'module/promises' 경로(fs/promises, dns/promises, stream/promises)에 promise 변형을 제공합니다. require('module')(./ 없음)은 내장 모듈을 먼저, 그다음 node_modules를 탐색합니다.

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()는 해석된 경로로 모듈을 캐시하므로 같은 모듈 코드가 한 번만 실행되고 내보내기가 재사용됩니다. 순환 의존은 동작하지만 먼저 로드된 모듈은 두 번째 모듈의 불완전(부분) exports 객체를 봅니다. 이를 감안해 설계하세요. 개발 중 핫 리로드는 delete require.cache로 합니다.

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

__dirname과 __filename은 현재 폴더/파일 경로를 주는 CommonJS 전용 전역입니다. ES 모듈에는 이런 전역이 없으므로 import.meta.url에서 fileURLToPath로 파생하세요. import.meta.url은 현재 모듈의 file:// URL이며 __filename의 ESM 대체물입니다.

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

npm init이 package.json을 스캐폴딩합니다. -y는 기본값으로 프롬프트를 건너뜁니다. npm set은 설정을 ~/.npmrc에 저장해 이후 초기화에 반영합니다. 스코프 패키지(@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에 추가됩니다. --save-dev는 devDependencies(배포되지 않는 테스트/빌드 도구)에 넣습니다. ^는 minor+patch 갱신을, ~는 patch만 허용합니다. -g는 CLI 도구를 글로벌 설치합니다.

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 scripts

package.json의 스크립트는 npm run <name>으로 실행합니다. start와 test는 특별합니다(npm start / npm test). pre/post 훅(pretest, postbuild)은 자동 실행됩니다. 하위 명령에 인자를 전달하려 --를 쓰세요. pnpm에서는 커스텀 스크립트에 "run"을 생략할 수 있습니다.

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 dlx가 pnpm의 대응물입니다.

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 갱신을 허용하고, ~(틸드)는 patch만 허용합니다. 락파일(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가 패키지를 레지스트리에 업로드합니다. npm version은 버전을 올리고 git 태그를 만들고 커밋합니다. 라이프사이클 훅(prepublishOnly, postpublish)이 릴리스 시 빌드/테스트를 자동화합니다. unpublish는 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의 { recursive: true }가 mkdir -p를 흉내 냅니다. readdir이 항목을 나열하고, { withFileTypes: true }는 isDirectory()/isFile()로 추가 stat 호출을 피하게 하는 Dirent 객체를 반환합니다. recursive+force를 준 fsp.rm이 비어 있지 않은 디렉터리의 rmdir을 대체합니다(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

파일 통계와 메타데이터

stat()는 size, mtime, 타입 헬퍼를 가진 Stats 객체를 반환합니다. fs.exists는(폐기 예정) 쓰지 말고, 경쟁 없는 존재 확인은 try/catch 안의 access()를 쓰세요. 하지만 파일을 직접 여는 편이 더 안전합니다. fsWatch는 change 이벤트를 내지만 플랫폼 간 일관성이 없을 수 있습니다.

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/promises(Node 10+)는 모든 fs 메서드의 promise 기반 버전을 제공하며 async/await에 이상적입니다. opendir()는 메모리 효율적 디렉터리 순회를 위한 비동기 이터레이터를 반환합니다. 이식성 있는 경로를 위해 path.join과 결합하세요. 모든 메서드는 오류 시 throw하므로 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);
}

Append, Rename, Delete

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은 플랫폼 구분자로 세그먼트를 연결하고 결과를 정규화합니다. path.resolve는 process.cwd()부터 시작하는 절대 경로를 만들며 절대 세그먼트가 이전 세그먼트를 버립니다. 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

path.parse는 경로를 root, dir, base, name, ext로 나누고, 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'

크로스 플랫폼 경로

path.sep과 path.delimiter는 OS마다 다릅니다. path.win32와 path.posix는 호스트 OS와 무관하게 특정 파서를 강제합니다. 다른 플랫폼의 경로 처리에 편리합니다. 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

ES 모듈은 file:// URL로 식별됩니다. url.pathToFileURL로 일반 경로를 dynamic import()용 URL로 바꾸고, url.fileURLToPath로 반대 변환을 합니다. ESM에서 import.meta.url은 이미 file URL이며 fileURLToPath로 경로로 바꾸면 __filename을 재현할 수 있습니다.

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()이 주어진 포트에서 연결 수락을 시작합니다. 하나의 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, () => {});

요청과 응답

req가 method, url, headers를 노출하고, res로 statusCode/헤더를 정한 뒤 write+end합니다. 응답을 마치려면 res.end를 반드시 호출해야 합니다. 큰 페이로드는 메모리에 전부 버퍼링하지 않도록 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로 구현하거나 URL 생성자로 pathname과 searchParams를 파싱하세요. 실제 앱은 Express나 프레임워크의 라우터를 쓰세요. URL 생성자는 상대 req.url을 파싱할 때 base가 필요합니다.

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를 받아 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 클라이언트

https.createServer에는 개인 키와 인증서가 필요합니다(예: Let's Encrypt). 나가는 요청에는 Node 18+가 전역 fetch()를 제공하므로 원시 http.get 콜백 API보다 이를 선호하세요. fetch는 promise 기반이며 async/await, 헤더, 스트림을 지원합니다.

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

Express가 가장 인기 있는 Node 웹 프레임워크입니다. app.get이 라우트 핸들러를 등록하고, res.send가 (Content-Type을 자동 감지해) 응답을 보내며, app.listen이 서버를 시작합니다. Express는 Node의 http 모듈에 라우팅, 미들웨어, 편의 헬퍼를 감쌉니다.

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}`);
});

라우팅과 라우트 파라미터

Express는 HTTP 메서드(get/post/put/delete)를 경로에 매칭합니다. :id가 URL 세그먼트를 req.params로 캡처하고, 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. 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 타입을 자동 감지하고 비디오/오디오의 range 요청을 지원합니다. 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)로 오류를 넘기거나 비동기 핸들러 안에서 throw하면 오류 처리 미들웨어가 트리거됩니다. 중앙 4인자 핸들러 하나를 마지막에 등록하세요. express.Router()가 라우트를 별도 파일로 모듈화하며, app.use('/prefix', router)로 마운트해 큰 API를 깔끔히 구성합니다.

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

스트림

Readable 스트림

Readable 스트림이 데이터를 생성합니다. flowing 모드에서는 'data' 이벤트가 청크를 자동 푸시하고, 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를 반환하므로, 백프레셔를 존중해 더 쓰기 전에 'drain' 이벤트를 기다리세요. end()가 더 이상 데이터가 없음을 알리고, 모두 플러시되면 'finish'가 발생합니다. process.stdout 자체가 writable 스트림입니다.

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

pipe()는 Readable을 Writable로 자동 백프레셔와 함께 전달합니다. stream.pipeline(promise 버전 권장)은 여러 스트림을 체이닝하고 오류를 제대로 전파하며 정리합니다. .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)를 구현하세요. objectMode로 Buffer 대신 객체를 푸시할 수 있습니다. zlib과 crypto가 준비된 transform을 제공합니다.

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'));

스트림 모드와 백프레셔

스트림은 pause()/resume()으로 flowing과 paused 모드를 오갑니다. 백프레셔는 느린 소비자가 생산자에게 속도를 줄이라고 알리는 것입니다. 비동기 이터레이션(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 소켓처럼). Transform은 출력이 입력에서 파생되는 Duplex입니다.

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은 0으로 채운 버퍼를 만듭니다(안전). Buffer.allocUnsafe는 속도를 위해 0 채우기를 생략하지만 오래된 메모리가 새어 나올 수 있으므로 모든 바이트를 덮어쓸 때만 쓰세요. 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

읽기와 쓰기

버퍼는 원시 바이트를 담습니다. 명시적 크기(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'

Concat과 Compare

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이 텍스트 기본입니다. base64/hex는 텍스트 속 바이너리(데이터 URL, 해시, 전송)에 흔합니다. 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

Buffer는 Uint8Array를 확장하므로 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)을 산출합니다.

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

이벤트 생성과 발행

EventEmitter가 Node의 pub/sub 핵심입니다. emit(eventName, ...args)가 이벤트를 발생시키고 on()이 구독합니다. 많은 내장 클래스(스트림, 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()는 발동 후 자동 제거되는 리스너를 등록합니다. 일회성 셋업에 좋습니다. 리스너를 제거하려 정확한 함수 참조를 유지해야 합니다(화살표 함수는 매번 새 참조를 만듦). removeAllListeners가 하나 또는 모든 이벤트의 리스너를 지웁니다. off는 removeListener의 별칭입니다.

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가 throw해 프로세스를 크래시합니다. EventEmitter에는 항상 오류 핸들러를 붙이세요. 특히 스트림과 HTTP 서버. captureRejections(Node 12+)가 비동기 리스너의 거부된 promise를 'error' 이벤트로 라우팅합니다.

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로 기다리려 once(ee, name)를 쓰세요. captureRejections를 켜면 거부된 비동기 리스너가 조용히 잃어버리는 대신 'error' 이벤트를 트리거합니다.

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는 리스너가 추가/제거될 때 발생하는 특수 이벤트로, 훅이나 프로파일링에 유용합니다. setMaxListeners가 누수 감지 임계값(기본 10)을 올립니다. 경고는 보통 리스너 정리를 잊었다는 뜻입니다. 이벤트 이름에는 오타를 방지하려 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 (셸, 버퍼링)

exec()는 명령을 셸을 통해 실행하고 stdout/stderr를 버퍼링합니다. 전체 출력을 한꺼번에 원하는 짧은 명령에 최선입니다. 셸을 생성하므로 글롭과 파이프가 확장됩니다. 사용자 입력을 명령 문자열에 절대 보간하지 마세요. 명령 주입 취약점입니다. spawn의 args 배열을 쓰세요.

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 (스트리밍, 셸 없음)

spawn()은 args 배열(셸 없음)로 프로세스를 시작하고 stdout/stderr를 스트리밍합니다. 크거나 장기 실행 출력에 안전하고 메모리 효율적입니다. args가 (셸을 거치지 않고) 직접 전달되므로 글롭 확장이나 주입 위험이 없습니다. 파이프라인을 위해 자식 스트림을 다른 스트림으로 파이프하세요.

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보다 안전합니다. fork()는 Node 프로세스를 생성하고 내장 IPC 채널(send/on('message'))을 열어 Node 프로세스 간 cluster 및 worker_threads 유사 메시지 전달의 기반입니다.

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'는 캡처합니다. 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

종료 코드와 시그널

'exit' 이벤트가 code(시그널로 죽으면 null)와 signal(정상 종료면 null)을 보고합니다. 'close'는 모든 stdio 스트림이 닫힌 뒤 발생하므로, 출력을 파이프했고 스트림이 플러시됐음을 알아야 할 때 쓰세요. 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

기본 클러스터링

cluster는 하나의 포트를 공유하는 여러 Node 프로세스를 fork해 CPU 코어 전반에 확장합니다. 프라이머리가 워커를 fork합니다(보통 os.cpus().length). 각 워커는 같은 스크립트를 실행하는 완전한 Node 프로세스입니다. 복원력을 위해 'exit'에서 워커를 재시작하세요. 로직 분기에는 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);
}

워커 관리

프라이머리는 'online'(프로세스 시작), 'listening'(서버 바인딩), 'disconnect', 'exit' 이벤트로 워커를 추적합니다. disconnect()는 워커를 죽이기 전 연결을 배출하므로 무중단 리로드에 씁니다. cluster.workers가 워커 ID를 Worker 객체에 매핑해 메시지를 보내거나 닫을 수 있게 합니다.

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' });
}

공유 서버 포트

모든 워커가 같은 포트에서 리슨하며 프라이머리가 들어오는 연결을 로드 밸런싱합니다. SCHED_RR(round-robin, 대부분 플랫폼 기본)이 균등 분배하고 SCHED_NONE은 OS에 맡깁니다. 상태는 워커 간 공유되지 않으므로 공유 세션/캐시에는 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)

워커 수명 주기와 IPC

cluster.fork()는 (child_process.fork처럼) IPC 채널을 열어 worker.send와 process.on('message')가 프라이머리와 워커 사이에서 JSON을 주고받게 합니다. 작업 디스패치나 우아한 종료 신호에 쓰세요. CPU 무거운 작업에는 메모리를 공유하고 IPC 오버헤드가 없는 worker_threads도 고려하세요.

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));
  }
});

우아한 리로드 (무중단)

롤링 재시작은 앱이 죽지 않게 워커를 하나씩 리로드합니다. 워커를 disconnect하고(새 연결 수락 중단), 배출 후 종료를 기다렸다가, 교체를 fork합니다. SIGHUP으로 트리거하세요. 항상 워커별 'shutdown' 메시지와 결합해 각 워커가 서버를 닫고 진행 중인 요청이 마친 뒤에만 종료하게 하세요.

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

비동기 프로그래밍

콜백과 error-first 관례

Node의 고전 비동기 패턴은 error-first 콜백입니다. 첫 인자가 오류(성공 시 null)이고 이후 인자가 결과입니다. 항상 err를 먼저 검사하고 실패 시 조기 반환하세요. 중첩이 깊어지면(콜백 지옥으로 알려짐) 확장이 어려우므로 현대 코드는 Promise와 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
});

Promise

Promise는 미래의 값을 나타냅니다. then()이 성공을, catch()가 거부를, finally()가 어느 쪽이든 실행을 다룹니다. then()을 체이닝해 값을 순차 변환합니다. util.promisify는 error-first 콜백 함수를 Promise를 반환하는 함수로 바꿔 레거시 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는 비동기 코드를 동기처럼 보이게 합니다. async 함수는 Promise를 반환하고, await가 정착까지 기다립니다. 거부 처리를 위해 await 호출을 try/catch로 감싸세요. 최상위 await는 ES 모듈에서 허용되며(플래그와 함께) CommonJS에서도 가능해 비동기 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

Promise.all은 병렬 실행 후 결과 배열로 resolve하지만, 어느 하나라도 거부하면 즉시 거부합니다(fast-fail). 전부 성공해야 할 때 쓰세요. Promise.allSettled는 결과와 무관하게 모든 promise를 기다려 {status, value/reason} 객체를 반환합니다. 부분 성공이 허용될 때 최선입니다.

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.race는 가장 먼저 정착하는 promise로 resolve 또는 reject합니다. 타임아웃과 미러 경주에 유용합니다. Promise.any는 첫 성공으로 resolve하고 모두 실패할 때만 거부합니다(AggregateError). 하나의 건강한 응답이면 충분한 이중화 엔드포인트에 이상적입니다.

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))
  ]);
}

순차 vs 병렬

루프에서 await하면 순차 실행됩니다(느림). promise 배열로 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

try/catch는 동기 오류와 (await와 함께) 비동기 거부를 처리합니다. finally는 return/throw와 무관하게 항상 실행되므로 핸들 닫기 같은 정리에 쓰세요. err.code를 검사해 특정 오류를 잡고, 인식 못한 것은 다시 throw해 예상치 못한 버그가 삼켜지지 않게 하세요.

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
  }
}

Error-First 콜백

error-first 콜백에서는 항상 err를 먼저 검사하고 조기 반환하세요. err가 설정됐을 때 data를 절대 쓰지 마세요. 콜백 API를 감쌀 때는 throw 대신 오류를 자기 콜백으로 전달하세요(콜백 안의 throw는 호출자가 잡지 못함). 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); }
  });
}

Uncaught Exception

uncaughtException은 모든 핸들러를 벗어난 동기 예외에서 발생합니다. 프로세스는 이미 오염되었으니 로그하고, 서버를 닫고, 종료하세요(프로세스 매니저가 재시작하게 두기). unhandledRejection은 잊힌 promise에서 발생하며 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 클래스

Error를 서브클래싱해 구조화된 필드(code, field, status)를 더하고 instanceof로 오류 타입을 구분하세요. 항상 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;
  }
}

오류 속성과 cause

모든 Error에는 message, name, stack이 있습니다. 안정적이고 기계가 읽을 수 있는 처리를 위해 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

Domains와 정리

비동기 정리에는 'beforeExit'를 쓰고(종료를 미룰 수 있음) '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 메서드

console은 log 이상을 제공합니다. table이 객체 배열을 렌더링하고, 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

--inspect가 V8 인스펙터를 시작해 Chrome DevTools(chrome://inspect)나 VS Code가 붙을 수 있게 합니다. --inspect-brk는 첫 줄에서 멈춰 시작 코드가 실행되기 전에 중단점을 잡게 합니다. 고전 'node inspect'는 브라우저를 쓸 수 없는 SSH 환경에 유용한 터미널 디버거입니다.

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 문

debugger 문은 디버거(DevTools 또는 VS Code)가 붙었을 때만 실행을 멈춥니다. 그 외에는 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"는 인스펙터를 내장한 채 프로그램을 실행하고, "attach"는 --inspect로 이미 시작된 프로세스에 연결합니다. skipFiles가 스텝핑에서 Node 내부를 숨깁니다. 파일 변경 시 자동 재실행에는 "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

경고와 스택 트레이스

--trace-warnings가 프로세스 경고(메모리 누수, 폐기 예정 API)의 스택을 출력합니다. --trace-deprecation은 레거시 API 사용을 드러내고, --throw-deprecation은 더 엄격한 CI를 위해 이를 하드 오류로 바꿉니다. --cpu-prof는 Chrome DevTools에서 열어 핫 함수를 찾을 수 있는 프로파일을 씁니다. 더 깊은 비동기 트레이스를 위해 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은 보안상 피하세요. 데이터를 점진 공급해 큰 파일을 버퍼링 없이 스트리밍할 수 있습니다. digest('hex')가 16진 문자열을 반환하고 '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 서명과 웹훅 검증(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)
  );
}

Random Bytes

crypto.randomBytes는 암호학적으로 안전한 랜덤 데이터를 만듭니다. 토큰, ID, 비밀에 사용하세요. 비동기 형태는 많은 바이트 생성 시 이벤트 루프 블로킹을 피합니다. crypto.randomInt는 편향 없는 랜덤 정수를 주고, randomUUID()가 RFC-4122 v4 UUID를 생성합니다. 보안 관련에는 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(논스)는 주어진 키로 암호화할 때마다 고유해야 하며(재사용 금지) 암호문 옆에 저장하세요. 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로 해싱하세요. 평범한 해시는 절대 아닙니다. pbkdf2(하드웨어가 좋아지면 반복 횟수를 올리세요)와 scrypt(메모리 하드, GPU 저항)가 Node에 내장되어 있습니다. 검증과 이후 파라미터 업그레이드를 위해 반복 횟수, 솔트, 해시를 함께 저장하세요. 타이밍 정보를 새지 않고 해시를 검사하려 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);
}

타이밍 안전 비교

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가 호스트 환경을 노출합니다. platform/arch/type이 이식성 검사를 위한 OS를 식별합니다. 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);

메모리

os.totalmem/freemem이 시스템 RAM을 보고하고, process.memoryUsage가 이 프로세스의 점유를 보고합니다. rss는 OS 수준 메모리이고 heapUsed는 살아 있는 JS 객체입니다. 누수를 위해 heapUsed를 지켜 보세요. 바이트를 MB로 바꾸려 1024*1024(1048576)로 나누세요. 힘이 한도 근처로 자라면 --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`);

네트워크 인터페이스

os.networkInterfaces()가 주소, MAC, 패밀리(IPv4/IPv6)와 함께 각 네트워크 인터페이스를 나열합니다. 'internal' 플래그가 루프백을 표시합니다. 서버 바인딩이나 로깅을 위해 머신의 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가 현재 사용자 신원을 주고, os.constants가 숫자 신호/errno/우선순위 값을 중앙화해 SIGTERM을 위한 15 같은 매직 넘버를 하드코딩하지 않게 합니다.

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가 명령줄 인자를 담습니다. argv[0]은 node 바이너리, argv[1]은 스크립트, 나머지는 사용자 인자입니다. 사용자 인자만 얻으려 앞 두 개를 잘라내세요. 장난감 스크립트 이상에는 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와 종료 코드

process.exit(n)는 I/O 버퍼가 플러시되기 전에도 즉시 종료합니다. process.exitCode를 설정하고 이벤트 루프가 자연히 배출되게 두는 편이 낫습니다. 0은 성공이고 0이 아닌 값은 셸과 CI에 실패를 알립니다. 관례 128+N은 시그널 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는 writable 스트림이며 write()는 (console.log와 달리) 줄바꿈을 더하지 않습니다. stdin은 'data' 이벤트나 비동기 이터레이션(가장 깔끔한 현대 패턴)으로 소비하는 readable 스트림입니다. 진단은 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'는 이벤트 루프가 비운 뒤 발생하며 동기 코드만 실행됩니다. 'beforeExit'는 비동기 작업을 할 수 있고 종료를 미룰 수 있습니다. SIGINT(Ctrl-C)와 SIGTERM(docker stop, kill)을 처리해 서버와 DB 연결을 우아히 닫으세요. 막힌 연결이 프로세스를 영원히 붙잡지 못하도록 항상 강제 종료 타임아웃을 두세요.

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

process가 신원(pid, ppid, platform, version)과 런타임 통계(uptime, memoryUsage, cpuUsage)를 노출합니다. 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 서버

net.createServer가 원시 TCP 서버를 만듭니다. 각 연결이 Socket(Duplex 스트림)을 주며 콜백을 호출합니다. 'data' 이벤트로 읽고 socket.write로 씁니다. 소켓의 'error'를 항상 처리하세요. 아니면 프로세스가 크래시합니다. TCP는 HTTP의 기반이며 커스텀 프로토콜, 게임, 프록시에 유용합니다.

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 클라이언트

net.connect(별칭 createConnection)이 TCP 클라이언트 소켓을 엽니다. 콜백이 연결 시 발생하고 '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
});

소켓 이벤트와 데이터

TCP는 메시지 프로토콜이 아니라 바이트 스트림입니다. 'data' 이벤트 하나가 메시지 하나가 아니며 데이터는 분할되거나 합쳐질 수 있습니다. 메시지를 직접 프레이밍해야 합니다(길이 접두어, 구분자, 또는 파서). 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);

쓰기와 Half-close

socket.write는 백프레셔를 존중합니다(가득 차면 false. 'drain' 대기). end()는 반쯤 닫습니다. 대기 중 쓰기를 플러시한 뒤 FIN을 보내지만 피어를 계속 읽습니다. 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

net.Server는 'connection'(클라이언트별), 'listening', 'error'(EADDRINUSE 처리), 'close'를 발생합니다. listen은 (Windows의 named pipe 포함) Unix 소켓용 경로를 받을 수 있으며 같은 호스트의 프로세스 간 빠르고 안전한 로컬 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)

setTimeout은 지연 후 한 번 실행되고 setInterval은 반복합니다. setImmediate는 같은 루프 턴에서 I/O 이벤트 뒤에 실행되며, 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된 타이머만 남으면 Node가 종료됩니다(프로세스를 붙잡으면 안 되는 주기적 정리에 편리). 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

util.format이 printf 스타일 자리표시자(%s %d %j %o %O %%)로 문자열을 만듭니다. util.inspect는 임의 객체를 렌더링하며 { depth: null, colors: true }로 전체 색상 덤프를 얻어 로그에 유용합니다. util.deprecate는 함수를 감싸 호출 시 DeprecationWarning을 발생시킵니다(--trace-deprecation으로 노출).

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

util.promisify는 error-first 콜백 함수를 Promise를 반환하는 함수로 감쌉니다. 레거시 콜백 API에서 async/await로 가는 다리입니다. 많은 코어 모듈이 이제 (fs/promises 같은) 네이티브 promise 버전을 제공하므로 그쪽이 바람직하지만 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

util.types는 신뢰할 수 있는 타입 검사(isPromise, isAsyncFunction, isRegExp, isMap)를 제공하며 크로스 리얼름과 서브클래스 경계 사례에서 instanceof보다 견고합니다. util.callbackify는 promisify의 반대로, promise 기반 함수를 콜백 스타일 API에 노출해야 할 때 유용합니다. util.MIMEType(Node 19+)이 MIME 타입을 파싱·조작합니다.

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 vs setImmediate

process.nextTick은 현재 동기 연산 직후, I/O '이전에' 실행됩니다. 따라서 재귀 nextTick 호출은 I/O를 무기히 굶길 수 있습니다(루프가 진행 못함). setImmediate는 I/O 후의 'check' 단계에서 실행됩니다. 이벤트 루프에 양보해 대기 중 I/O가 정착하게 하려 setImmediate를 선호하고, nextTick은 어떤 I/O 콜백보다 먼저 일어나야 하는 정리에만 남겨 두세요.

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.