ES5 스타일 모듈 참조
const path = require('path');
// import path from 'path' 와 같음
- 파라미터의 제한 없음
- 조합된 경로 문자열에 해당하는 Path가 실제로 존재하는지는 상관 없음
const currentPath = path.join('C:/users/hello/world', 'myphoto', '../photo.jpg');
// 파라미터 마지막에 ../photo기 때문에 2번째 myphoto는 사라진다
C:/users/hello/world/photo.jpg
> path.dirname(currentPath);
`C:\users\hello\wrold`
> path.basename(currentPath);
`photo.jpg`
> path.extname(currentPath);
`.jpg`
경로의 성분을 JSON 형태로 한번에 분할
> const parse = path.parse(currentPAth);
{
root: 'C:\\',
dir: 'C:\\users\\hello\\wrold',
base: 'photo.jpg',
ext: '.jpg',
name: 'photo'
}
> console.debug('root: ' + parse.root);
root: C:\
> console.debug('dir ' + parse.dir);
dir C:\users\hello\wrold
> console.debug('name ' + parse.name);
name photo
> console.debug('ext ' + parse.ext);
ext .jpg
주어진 경로가 절대 경로인지 상대 경로인지 알아내려면 isAbsolute()
함수 사용
> path.isAbsolute("C:/users/hello/world/photo.jpg")
true
> path.isAbsolute("./photo.jpg")
false
./, ../, / 문자를 남용한 경로는 파일 시스템에서 정확히 어느 위치를 나타내는지 햇갈리는 경우가 있습니다. 이럴 때는 normalize()
함수를 사용하여 불필요한 부분을 정리하여 경로를 단순화 할 수 있습니다.
> path.normalize("C:/users/../hello/world//photo.jpg")
'/C:\hello\world\photo.jpg'