[ TIL 221202 ] Node.js의 path 모듈로 경로 다루기

ponyo·2022년 12월 2일
0

Node

목록 보기
1/7

불러오기

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'

참고한 글 : https://www.daleseo.com/js-node-path/

profile
😁

0개의 댓글