Node.js API (nodejs.org)
Node.js API 문서를 모델이 자주 틀리는 부분(안전하지 않은 기본값, 함정, 폐기 항목) 중심으로 압축합니다. 각 주장은 nodejs.org 페이지로 끝납니다.
대상 버전
읽은 문서는 v26.13.0입니다. 많은 프로젝트가 v24 LTS 라인을 실행하므로, 참조에는 새로운 기능을 표시합니다. "v25.x 추가" 또는 "v26.x 추가"는 백포트 버전이 명시되지 않은 한 v24에 없음을 의미합니다. https://nodejs.org/docs/latest/api/
플래그된 기능을 사용하기 전에 process.version을 확인하거나 기능 감지(process.features.typescript, process.features.require_module)를 사용하세요. https://nodejs.org/docs/latest/api/process.html
아래 규칙을 읽은 다음, 해당 참조 파일을 여세요.
최우선 규칙
- 파일을 열기 전에
access(),exists()또는stat()를 절대 호출하지 마세요: 직접 열고ENOENT/EEXIST를 처리하세요 (독점 생성을 위해 플래그'wx'사용). https://nodejs.org/docs/latest/api/fs.html#fsaccesspath-mode-callback - 모든
FileHandle을 명시적으로 닫고, 이상적으로는await using을 사용하세요. GC에 남겨진FileHandle은 오류를 발생시킵니다. https://nodejs.org/docs/latest/api/deprecations.html#DEP0137 .pipe()체인이 아닌pipeline()으로 스트림을 구성하고,write()가false를 반환하는 것을 존중하세요. https://nodejs.org/docs/latest/api/stream.html#readablepipedestination-options- 모든 emitter, stream, socket, request 및 child process에
'error'리스너를 추가하세요: 처리되지 않은'error'는 프로세스를 중단시킵니다. https://nodejs.org/docs/latest/api/events.html#error-events err.message가 아닌err.code로 분기하세요. https://nodejs.org/docs/latest/api/errors.html#errorcodeprocess.exit()를 호출하는 대신process.exitCode를 설정하세요.process.exit()는 stdout을 자를 수 있습니다. https://nodejs.org/docs/latest/api/process.html#processexitcode'uncaughtException'이후 작업을 재개하지 마세요: 동기적으로 정리하고 종료하세요. https://nodejs.org/docs/latest/api/process.html#warning-using-uncaughtexception-correctly- 레거시
process.nextTick()보다queueMicrotask()를 선호하세요. https://nodejs.org/docs/latest/api/process.html#when-to-use-queuemicrotask-vs-processnexttick - 셸 없이
execFile()/spawn()을 사용하세요.shell: true로args를 전달하면 이스케이프되지 않습니다. https://nodejs.org/docs/latest/api/deprecations.html#DEP0190 - 모든 HTTP 클라이언트 응답 본문을 소비하고(최소한
res.resume()),req.on('error')를 연결하고,timeout이 중단되지 않음을 기억하세요:destroy()를 호출하세요. https://nodejs.org/docs/latest/api/http.html#class-httpclientrequest - 리버스 프록시가 없는 서버에서
headersTimeout을 0이 아닌 값으로 유지하세요. https://nodejs.org/docs/latest/api/http.html#serverheaderstimeout - WHATWG
URL을 사용하세요.url.parse()는 폐기되었으며 이에 대한 CVE는 발행되지 않습니다. https://nodejs.org/docs/latest/api/deprecations.html#DEP0169 path.isAbsolute()는 경로 탐색을 막지 않으며,path.normalize()는 어휘적이며 시스템이 경로를 해석하는 방식을 변경할 수 있습니다: 해석한 후 결과가 루트 내에 머무는지 확인하세요. https://nodejs.org/docs/latest/api/path.html#pathisabsolutepath- 기본적으로
Buffer.alloc()을 사용하고, 뷰에는Buffer.subarray()를 사용하며, 절대new Buffer()를 사용하지 마세요. https://nodejs.org/docs/latest/api/deprecations.html#DEP0005 - 동일한 길이의 버퍼에서
crypto.timingSafeEqual()로 비밀을 비교하세요. https://nodejs.org/docs/latest/api/crypto.html#cryptotimingsafeequala-b - zlib로 신뢰할 수 없는 데이터를 압축 해제할 때
maxOutputLength를 설정하세요 (기본값buffer.kMaxLength). https://nodejs.org/docs/latest/api/zlib.html#class-options package.json에"type"을 설정하고,"exports"조건에서"default"를 마지막에 두세요. https://nodejs.org/docs/latest/api/packages.html#determining-module-system- ESM의
require()는 동기 그래프에서 작동합니다. 그래프 어디에서든 최상위await는ERR_REQUIRE_ASYNC_MODULE을 발생시킵니다. https://nodejs.org/docs/latest/api/modules.html#loading-ecmascript-modules-using-require - 타입 스트리핑은
.ts를 타입 검사 없이 실행합니다:enum금지, 명시적.ts확장자,import type,tsconfigpaths금지. v25.2.0부터 안정적이며(v24.12.0으로 백포트됨),process.features.typescript로 감지하세요. https://nodejs.org/docs/latest/api/typescript.html#typescript-features , https://nodejs.org/docs/latest/api/typescript.html#type-stripping - 모듈 훅을
module.registerHooks()로 등록하세요.module.register()는 v26에서 폐기되었습니다. https://nodejs.org/docs/latest/api/deprecations.html#DEP0205 async_hooks.createHook()보다AsyncLocalStorage를 선호하세요. https://nodejs.org/docs/latest/api/async_hooks.htmlnode:test에서 하위 테스트에await t.test()를 사용하세요. https://nodejs.org/docs/latest/api/test.html#subtestsnode:vm과 WASI는 샌드박스가 아니며, 권한 모델은 신뢰할 수 없는 코드를 실행하는 안전한 방법이 아닙니다: 그 목적으로 절대 사용하지 마세요. https://nodejs.org/docs/latest/api/permissions.html#process-based-permissionsAbortSignal이 아닌using/await using으로 서버, 스트림 및 자식 프로세스를 폐기하세요. 취소 및 시간 초과에는 시그널을 유지하세요. https://nodejs.org/docs/latest/api/deprecations.html#DEP0209dns.lookup()는 DNS 쿼리가 아닌 스레드 풀의getaddrinfo입니다. https://nodejs.org/docs/latest/api/dns.html#implementation-considerations- 풀 크기를
os.availableParallelism()으로 조정하세요. https://nodejs.org/docs/latest/api/os.html#osavailableparallelism node:sqlite: 매개변수를 바인딩하고, SQL에 절대 문자열 보간하지 마세요. https://nodejs.org/docs/latest/api/sqlite.html#binding-parameters- 폐기 항목을 표면화하려면
--pending-deprecation으로 CI를 실행하세요. https://nodejs.org/docs/latest/api/deprecations.html
참조 파일
| 파일 | 용도 |
|---|---|
| references/fs.md | TOCTOU, FileHandle, readFile/writeFile, rm, glob, fs.watch |
| references/path-and-url.md | path, 경로 탐색, file: URL, WHATWG URL, querystring |
| references/crypto.md | KeyObject, timingSafeEqual, 해싱, pbkdf2, scrypt, 취약한 알고리즘 |
| references/ciphers-and-webcrypto.md | AEAD 태그, GCM, 키 래핑, subtle, 키 형식 |
| references/streams.md | pipeline, 역압, highWaterMark, finished, 스트림 구현 |
| references/web-streams-and-stream-iter.md | Web Streams, node:stream/iter |
| references/buffer.md | alloc 대 allocUnsafe, 인코딩, Blob |
| references/zlib.md | 압축 해제 폭탄, 플러시, Zstd |
| references/http-client.md | http.request, 에이전트, keep-alive, 프록시 |
| references/http-server.md | 시간 초과, 정상 종료, HTTPS 서버 |
| references/net-dns-dgram.md | TCP, BlockList, dns.lookup 대 resolve, UDP |
| references/tls.md | SNI, 암호, CA 저장소, 세션 재개 |
| references/http2.md | 보안 서버, allowHTTP1, 강화 |
| references/process.md | 종료 코드, 시그널, uncaughtException, 거부 |
| references/cli-and-env-files.md | NODE_OPTIONS, --env-file, --watch |
| references/permissions.md | --permission, 알려진 격차 |
| references/errors.md | error.code, cause, 오류 코드 |
| references/events-and-timers.md | captureRejections, events.once, EventTarget, 타이머 |
| references/async-context-and-diagnostics-channel.md | AsyncLocalStorage, diagnostics_channel |
| references/util-and-console.md | util, Console |
| references/os-tty-readline-repl.md | os, tty, readline, REPL |
| references/test-runner.md | 하위 테스트, 격리, 커버리지, 리포터, 모의 객체 |
| references/assert-and-bench.md | node:assert/strict, 깊은 동등성, node:bench |
| references/esm-and-commonjs.md | "type", JSON 가져오기, import.meta, require(esm) |
| references/packages.md | "exports", "imports", 조건, 이중 패키지 |
| references/typescript-and-module-hooks.md | 타입 스트리핑, registerHooks, findPackageJSON |
| references/globals.md | fetch, AbortSignal, 전역 객체 |
| references/child-process.md | execFile 대 exec, maxBuffer, IPC |
| references/worker-threads-and-cluster.md | 풀, 전송 목록, 클러스터 |
| references/vm-wasi-vfs.md | vm, WASI, node:vfs |
| references/performance-and-profiling.md | perf_hooks, 힙 스냅샷 |
| references/debugging-and-reports.md | 인스펙터, 진단 보고서 |
| references/sqlite.md | Database, 기본값, 바인딩, 타입 변환 |
| references/sea-and-native.md | SEA, Node-API 규칙, node:ffi |
| references/deprecations.md | DEP 코드, 제거된 API, codemods |
읽은 페이지, 버전 및 가져온 날짜는 SOURCES.md에 나열되어 있습니다.