본문 바로가기

언어/Node.js

[ Node.js ] file 확장자 제외하고 이름만 가져오기

반응형

Node.js에서 파일에서 확장자를 제외하고 파일명만 가져오려면 path 모듈의 basename 함수와 extname 함수를 사용할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다:

const path = require('path');

const filePath = '/path/to/file/example.txt';

// 확장자를 제외한 파일명만 가져오기
const fileName = path.basename(filePath, path.extname(filePath));

console.log(fileName);  // 'example'

설명:

  • path.extname(filePath)는 파일의 확장자를 반환합니다.
  • path.basename(filePath, path.extname(filePath))는 파일명에서 확장자를 제외한 부분만 반환합니다.

이 방법을 사용하면 파일 경로에서 확장자를 제거한 순수한 파일명을 얻을 수 있습니다.

반응형