Node.js Path - Path 모듈 설치 및 사용 방법, 메서드 설명

반응형

 

패스 모듈이란? (Path Module)

  • 파일 시스템과 관련된 작업을 쉽게 수행할 수 있도록 도와주는 기능을 제공하는 모듈
  • Node.js에서 파일 경로와 관련된 작업을 수행 할 때 유용하게 사용
  • 의외로 혼동하기 쉬운 경로 설정에 대한 오류율을 최소화하는데 사용
  • 즉, 오류를 줄이고 편하게 경로를 설정하기 위해서 사용함

패스 모듈 설치 및 사용 방법 (Path Module Install&Use)

설치

  • 패스 모듈은 Node.js의 자체 모듈이므로 별도의 설치가 필요하지 않음
  • 즉, Node.js 설치 시 기본적으로 포함되어 있음

사용 방법

  • 모듈을 사용하기 위해 require() 함수를 이용하여 모듈 호출
// 패스 모듈 호출
const path = require('path');

 

  • 메서드를 이용하여 파일 경로 구성
  • 예시) 경로를 파싱하여 파일 경로 구성 (parse 메서드)
console.log( path.parse(__dirname) );


패스 모듈 메서드

경로 파싱(parse)

  • 파일 경로를 파싱하여 파일 경로를 구성하는 요소들은 분리하여 반환
  • 반환되는 객채에는 파일 경로의 디렉토리 경로, 파일 이름, 확장자 등이 포함
const path = require('path');

const filePath = '/home/user/Documents/example.txt';

const parsed = path.parse(filePath);

console.log(parsed.dir);    // '/home/user/Documents'
console.log(parsed.base);   // 'example.txt'
console.log(parsed.ext);    // '.txt'

경로 결합(join)

  • 여러 개의 경로를 조합하여 새로운 경로를 생성
  • 파일 경로를 생성할 때 유용
const path = require('path');

const dirPath = '/home/user/Documents';
const fileName = 'example.txt';

const filePath = path.join(dirPath, fileName);

console.log(filePath);    // '/home/user/Documents/example.txt'

경로 조합(resolve)

  • 절대 경로를 생성하기 위해 여러 개의 경로를 조합
  • 인자 중 하나가 절대 경로일 때 이전 모든 인자를 무시하고 해당 절대 경로 반환
    • join() 메서드와의 차이점
const path = require('path');

const dirPath = '/home/user/Documents';
const fileName = 'example.txt';

const filePath = path.resolve(dirPath, fileName);

console.log(filePath);    // '/home/user/Documents/example.txt'

경로 정규화(nomalize)

  • 파일 경로를 정규화하여 여러 경로가 동일한 경로를 가리키도록 설정
  • 상대적 경로와 절대 경로의 경우, 서로 동일한 파일을 가리키지만 서로 다른 경로이기 때문
const path = require('path');

const filePath1 = '/home/user/Documents/./example.txt';
const filePath2 = '/home/user/Documents/example.txt';

console.log(path.normalize(filePath1));    // '/home/user/Documents/example.txt'
console.log(path.normalize(filePath2));    // '/home/user/Documents/example.txt'

기타 메서드

  • path.basename(경로[, ext]
    • 파일 경로에서 파일 이름 반환
    • ext 인자 사용 시, 확장자 제거
  • path.dirname(경로)
    • 파일 경로에서 디렉토리 경로 반환
  • path.extname(경로)
    • 파일 경로에서 파일의 확장자 반환
  • path.isAbsolute(경로)
    • 경로가 절대 경로인지 여부를 반환
  • path.relative(from, to)
    • 첫 번째 인자 경로에서 두 번째 인자 경로까지의 상대 경로를 반환
  • path.sep
    • 파일 시스템에서 사용하는 디렉토리 구분자를 반환
    • windows : \
    • macOS, Linux : /

참고

 

반응형