Node
Path모듈
한츄
2023. 12. 21. 19:01
path.resolve("/Users", "../user", "test.txt")
// '/user/test.txt'
운영체제별 경로를 해결하기 위해 만들어진 모듈입니다.
유닉스 계열과 윈도우는 디렉토리를 표현하는 방법과 문자가 다릅니다.
- 유닉스 계열
$ pwd
/Users/user
- 윈도우
$ cd
C:\Users\user
사용해보기
path 모듈은 Node.js의 내장 모듈로 별도의 라이브러리 설치없이 사용이 가능합니다.
const path = require("path");
경로만들기
- join() 함수
여러 개의 문자열을 가변 인자로 받아서 하나의 완전한 경로로 조합해줍니다.
path.join("Users", "user", "test.txt")
// 'Users/user/test.txt'
- resolve() 함수
터미널에서 cd 명령어를 연속해서 사용하는 것 처럼 작동합니다
/과 \을 구분하지 않고 동작하며 항상 절대경로를 반환합니다.
path.resolve("/Users", "../user", "test.txt")
// '/user/test.txt'
디렉토리얻기
- dirname() 함수
주어진 경로에서 파일 이름을 제외한 디렉토리 부분을 얻을 수 있습니다.
path.dirname("/Users/user/test.txt")
// '/Users/user'
파일이름 얻기
- basename() 함수
path.dirname("/Users/user/test.txt")
// '/Users/user'
두번째 인자로 .을 포함한 확장자를 넘기면 순수한 파일 이름만 얻게 됩니다.
path.basename("/Users/user/test.txt", ".txt")
//'test'
파일 확장자 얻기
- extname() 함수
path.extname("/Users/user/test.txt")
//'.txt'
절대경로인지 확인하기
- isAbsoulte() 함수
path.isAbsolute("/Users/user/test.txt")
// true
path.isAbsolute("./test.txt")
// false
절대경로화 하기
- normalize() 함수
path.normalize("/Users/../user/test.txt")
// '/user/test.txt'
상대경로구하기
- relative() 함수
함수의 기준이되는 경로를 첫번째 인자로 넣고, 대상이 되는 경로를 두번째 인자로 넣으면 상대경로를 구해줍니다.
path.relative("/Users", "/Users/user/test.txt")
//'user/test.txt'
path.relative("/Users/user/test.txt", "/Applications")
// '../../../Applications'