지식보부상님의 공부 일지

Dolt Node.js [03] 파일 관리하기 본문

KB IT's Your Life/Vue

Dolt Node.js [03] 파일 관리하기

지식보부상님 2025. 4. 23. 09:18

[03] 파일 관리하기 - path, File System 모듈

(1) path 모듈

◈ path 모듈

- 파일 경로나 디렉터리 경로 다루는 모듈

 

◈ 경로를 다루는 주요 함수, 메서드

(1) const path = require('모듈명'); 

  - path 모듈 가져오는 함수

(2) path.join(경로1, 경로2, ... ); 

 - 경로 합치는(연결하는) 메서드

// path 모듈 함수 다루는 예제
const path = require('path');

// 경로 연결하기
// some\work\ex.txt
const fullPath = path.join('some', 'work', 'ex.txt'); 
console.log(fullPath);

 

◈ path.dirname(경로);

 - 경로만 추출하는 메서드 (파일명 제외)

 - 경로의 마지막은 파일명으로 생각하고, 그 앞까지만 경로로 판단함

// 경로만 추출하기
const dir = path.dirname(__filename);
console.log(`경로만: ${dir}`);

 

◈ basename(경로), basename(경로, 확장자)

 - path.basename(경로): 경로 제외한 파일명만 리턴

 - path.basename(경로, 확장자): 지정한 확장자 제외 파일명 리턴

// basename 예제
const path = require('path');

const fn = path.basename(__filename);
const fn2 = path.basename(__filename, '.js');

console.log(`파일 이름: ${fn}`);
console.log(`파일 이름(확장자 제외): ${fn2}`);

 

◈ extname(경로)

 - path.extname(경로): 파일의 확장자 추출하여 리턴

// extname 사용 예제
const path = require('path');

const ext = path.extname(__filename);
console.log('파일 확장자:', ext);	// .js
console.log(path.basename(__filename, ext));	// 확장자제외 파일명 출력

 

◈ parse (경로)

 - path.parse(경로) : 경로를 객체로 반환

{
    root,    // 루트 디렉터리
    dir,     // 디렉터리 경로
    base,    // 파일명, 확장명
    ext,     // 확장자명
    name     // 파일명 (확장자 제외)
}