Programming/Node.js

[Node.js] 기본 모듈 Path란? / 사용법

MOONCO 2021. 2. 26. 15:06

Path란?

파일과 폴더의 경로 작업을 위한 기능을 제공하는 Node.js 기본 모듈

 

경로를 가장 짧은 방식으로 최적화 하기 (normalize)

// path 모듈 불러오기
const path = require("path");

// path.normalize : 최적화해서 저장
let myPath = path.normalize("/this/is//a/my/.././path/normalize");

// 결과 출력
console.log(myPath);

// => /this/is/a/path/normalize

 

운영체제에 맞춰 경로 지정하기 (join)

const path = require("path");

// path.join : string 형식의 인자들을 현재 운영체제에 맞춰 경로를 설정해줌
myPath = path.join("/this", "is", "a", "////path//", "join");

console.log(myPath);

// => /this/is/a/path/join

 

운영체제에 맞춰 경로 지정함과 동시에, 최적화까지 같이 하기 (resolve)

const path = require("path");

// path.resolve : string형식의 인자들을 합쳐서, 운영체제에 맞게 최적화된 경로를 설정해준다.
myPath = path.resolve("/this", "is/a", "../.", "path", "resolve");

console.log(myPath);

// => /this/is/path/resolve




myPath = path.resovle("wwwroot", "static_files/png/", "../gif/image.gif");

console.log(myPath);

// => 현재위치/wwwroot/static_files/gif/image.gif

 

현재 작업 파일, 폴더 출력하기 (dirname, basename)

const path = require("path");

// __filename : 현재 파일 경로
// __dirname : 현재 폴더 경로
console.log(__filename);
console.log(__dirname);




// path.dirname : 폴더 경로 출력
myPath = path.dirname("/foo/bar/baz/asdf/image.png");

console.log(myPath);

// => /foo/bar/baz/asdf




// path.basename : 파일 출력
myPath = path.basename("/foo/bar/baz/asdf/image.png");
console.log(myPath);

// => image.png




// 옵션으로 확장자 제거
myPath = path.basename("/foo/bar/baz/asdf/image.png", ".png");
console.log(myPath);

// => image

 

경로 분석해서, 형식별로 나누기 ( parse )

const path = require("path");

// path.parse : 경로를 분석해서, 형식에 따라 분류해준다.
myPath = path.parse("/home/user/dir/file.txt");
console.log(myPath);

// =>
{
    // 루트 경로
    root : '/',
    // 폴더 경로
    dir: '/home/user/dir',
    // 파일
    base: 'file.txt',
    // 파일 확장자
    ext: '.txt',
    // 파일 이름
    name: 'file'
}

 

파일 형식 가져오기

const path = require("path");

// path.extname('파일') : 파일을 분석해서, 확장자를 반환해준다.

myPath = path.extname("/home/user/dir/file.txt");
console.log(myPath);

// txt 출력

 

반응형