Node.js에서 윈도우즈 외부 경로 파일 읽기 — 윈도우즈에선 / 도 구분자로 받지만 path 메서드는 \ 로 만든다.1

const path = require('path')
const fs = require('fs').promises

// 슬래시 사용 (윈도우즈는 / 와 \ 를 둘 다 구분자로 받는다)
// ('C:/Users/username/Documents/file.txt')

// 또는 백슬래시 이스케이프
// ('C:\\Users\\username\\Documents\\file.txt')

// 권장: path.join 사용 (크로스 플랫폼)
path.join(process.env.USERPROFILE, 'Documents', 'file.txt')

// path.resolve로 절대 경로 생성
path.resolve('../../Documents/file.txt')

path.normalize()는 디렉토리 트래버설을 막지 못한다 — .. 를 풀기만 해서 normalize('../../etc/passwd') 는 그대로 '../../etc/passwd' 다.2 사용자 입력이면 path.resolve(base, input) 결과가 base + path.sep 로 시작하는지 확인한다.


Footnotes

  1. Path - Node.js: “On Windows, both the forward slash (/) and backward slash (\) are accepted as path segment separators; however, the path methods only add backward slashes (\).” ↩

  2. path.normalize - Node.js: “The path.normalize() method normalizes the given path, resolving '..' and '.' segments.” ↩

`#520`