시작하기
REPL과 스크립트 실행
REPL(Read-Eval-Print Loop)은 Node.js 코드를 실험하는 인터랙티브 셸입니다. 개발 자동 재시작에는 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는 런타임 경고의 스택 트레이스를 보여 주고, NODE_OPTIONS는 CLI 플래그를 담는 단일 환경 변수로 컨테이너나 npm 스크립트 안에서 편리합니다. --inspect는 Chrome DevTools 디버거를 엽니다.
# 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과 프로젝트 초기화
npm init이 package.json을 만듭니다. "type" 필드가 기본 모듈 시스템을 결정합니다. "module"은 .js 파일에서 ES 모듈 문법을, "commonjs"(기본)는 require/module.exports를 유지합니다. "main"은 패키지가 require될 때의 진입점입니다.
# 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" 필드가 결정합니다.
# 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에 해당).
# 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 도구가 글로벌 설치 시 명령을 노출하는 데 씁니다.
#!/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
require()는 CommonJS 모듈을 동기 로드하고 그 module.exports를 반환합니다. 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
ES Modules는 정적 import/export를 씁니다. 바인딩은 live이며 호이스팅됩니다. default export는 어떤 이름으로든(중괄호 없이) 임포트되고, named export는 이름이 일치하는 중괄호가 필요합니다. 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()
import()는 CJS와 ESM 모두에서 쓸 수 있는 동적·비동기 임포트입니다. 모듈 네임스페이스로 resolve되는 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 불필요. 대부분 콜백 API를 노출하며 많은 모듈이 'module/promises' 경로(fs/promises, dns/promises, stream/promises)에 promise 변형을 제공합니다. require('module')(./ 없음)은 내장 모듈 을 먼저, 그다음 node_modules를 탐색합니다.
// 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로 합니다.
// 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 대체물입니다.
// 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
npm init이 package.json을 스캐폴딩합니다. -y는 기본값으로 프롬프트를 건너뜁니다. npm set은 설정을 ~/.npmrc에 저장해 이후 초기화에 반영합니다. 스코프 패키지(@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에 추가됩니다. --save-dev는 devDependencies(배포되지 않는 테스트/빌드 도구)에 넣습니다. ^는 minor+patch 갱신을, ~는 patch만 허용합니다. -g는 CLI 도구를 글로벌 설치합니다.
# 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 scripts
package.json의 스크립트는 npm run <name>으로 실행합니다. start와 test는 특별합니다(npm start / npm test). pre/post 훅(pretest, postbuild)은 자동 실행됩니다. 하위 명령에 인자를 전달하려 --를 쓰세요. pnpm에서는 커스텀 스크립트에 "run"을 생략할 수 있습니다.
// 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 dlx가 pnpm의 대 응물입니다.
# 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를 쓰세요.
# 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를 선호하세요.
# 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의 { recursive: true }가 mkdir -p를 흉내 냅니다. readdir이 항목을 나열하고, { withFileTypes: true }는 isDirectory()/isFile()로 추가 stat 호출을 피하게 하는 Dirent 객체를 반환합니다. recursive+force를 준 fsp.rm이 비어 있지 않은 디렉터리의 rmdir을 대체합니다(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파일 통계와 메타데이터
stat()는 size, mtime, 타입 헬퍼를 가진 Stats 객체를 반환합니다. fs.exists는(폐기 예정) 쓰지 말고, 경쟁 없는 존재 확인은 try/catch 안의 access()를 쓰세요. 하지만 파일을 직접 여는 편이 더 안전합니다. fsWatch는 change 이벤트를 내지만 플랫폼 간 일관성이 없을 수 있습니다.
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로 감싸세요.
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가 파일을 주어진 길이로 다시 조정합니다.
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은 플랫폼 구분자로 세그먼트를 연결하고 결과를 정규화합니다. path.resolve는 process.cwd()부터 시작하는 절대 경로를 만들며 절대 세그먼트가 이전 세그먼트를 버립니다. 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
path.parse는 경로를 root, dir, base, name, ext로 나누고, 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'크로스 플랫폼 경로
path.sep과 path.delimiter는 OS마다 다릅니다. path.win32와 path.posix는 호스트 OS와 무관하게 특정 파서를 강제합니다. 다른 플랫폼의 경로 처리에 편리합니다. 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
ES 모듈은 file:// URL로 식별됩니다. url.pathToFileURL로 일반 경로를 dynamic import()용 URL로 바꾸고, url.fileURLToPath로 반대 변환을 합니다. ESM에서 import.meta.url은 이미 file URL이며 fileURLToPath로 경로로 바꾸면 __filename을 재현할 수 있습니다.
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);HTTP 서버
기본 HTTP 서버
http.createServer가 서버를 반환하며 콜백이 모든 요청을 처리합니다. res.writeHead가 상태 코드와 헤더를 정하고, res.end가 본문을 보내 응답을 마칩니다. listen()이 주어진 포트에서 연결 수락을 시작합니다. 하나의 Node 프로세스가 이벤트 루프로 많은 동시 요청을 처리합니다.
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로 파이프하세요.
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가 필요합니다.
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을 설정하세요. 프로덕션에서는 메모리 고갈을 막으려 바디 크기를 제한하세요.
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()를 호출하면 진행 중인 요청이 프로세스 종료 전에 마칩니다.
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, 헤더, 스트림을 지원합니다.
// 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();Express 기본
Express 설치와 Hello World
Express가 가장 인기 있는 Node 웹 프레임워크입니다. app.get이 라우트 핸들러를 등록하고, res.send가 (Content-Type을 자동 감지해) 응답을 보내며, app.listen이 서버를 시작합니다. Express는 Node의 http 모듈에 라우팅, 미들웨어, 편의 헬퍼를 감쌉니다.
// 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로 같은 경로의 여러 메서드를 체이닝할 수 있습니다. 라우트는 등록 순서대로 매칭되므로 구체적인 라우트를 일반적인 것보다 먼저 정의하세요.
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가 첫째)이며 마지막에 등록해야 합니다.
// 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(파싱된 페이로드)가 세 가지 주요 요청 데이터 원천입니다.
// 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 의존 버그를 피하려 항상 절대 경로를 쓰세요.
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를 깔끔히 구성합니다.
// 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스트림
Readable 스트림
Readable 스트림이 데이터를 생성합니다. flowing 모드에서는 'data' 이벤트가 청크를 자동 푸시하고, paused 모드에서는 read()를 명시 호출합니다. 'error'는 항상 처리하세요. 미처리 오류 이벤트는 프로세스를 크래시합니다. highWaterMark가 내부 버퍼 크기를 제어합니다.
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 스트림입니다.
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을 선호하세요.
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을 제공합니다.
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 대신 문자열을 받으려 항상 인코딩을 설정하세요.
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입니다.
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(); }
}Buffer
Buffer 생성
Buffer.alloc은 0으로 채운 버퍼를 만듭니다(안전). Buffer.allocUnsafe는 속도를 위해 0 채우기를 생략하지만 오래된 메모리가 새어 나올 수 있으므로 모든 바이트를 덮어쓸 때만 쓰세요. Buffer.from은 문자열/배열/버퍼를 변환합니다. 레거시 'new Buffer()' 생성자는 보안 우려로 폐기 예정입니다.
// 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)가 바이트를 문자열로 디코딩합니다. 이전 바이트를 덮어쓰지 않도록 항상 오프셋을 전달하세요.