Node.js파일 시스템

path와 URL 다루기

`path` 모듈과 `import.meta.url` 기반 URL 변환을 함께 정리해 파일 경로 실수를 줄이는 카드입니다.

마지막 수정 2026년 3월 19일

기본 패턴

javascript
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const outputPath = path.join(__dirname, "dist", "result.json");

설명

  • ESM에서는 CommonJS의 __dirname이 없으므로 import.meta.url을 URL로 받고, 다시 파일 경로로 바꿔야 합니다.
  • path.join은 운영체제마다 다른 구분자를 안전하게 처리합니다.
  • 경로 계산은 문자열 더하기보다 path 모듈을 쓰는 습관이 훨씬 안전합니다.

짧은 예제

javascript
const ext = path.extname("report.csv");
const base = path.basename("/tmp/report.csv");

빠른 정리

함수역할
path.join(a, b)경로 합치기
path.dirname(file)상위 폴더
path.basename(file)파일명
fileURLToPath(import.meta.url)URL -> 파일 경로

주의할 점

상대 경로를 현재 작업 폴더 기준으로만 생각하면 배포 환경에서 깨질 수 있으니, 파일 옆 기준 경로와 cwd 기준 경로를 구분해 두세요.