본문 바로가기
카테고리 없음

[Node.js] 해당 파일이 일반 파일인지 폴더인지 구분하기

by teamnova 2023. 11. 18.
728x90

안녕하세요. 

node js에서 해당 파일이 일반파일인지 폴더인지 구분하는 방법에 대해 말씀드리겠습니다!

 

 

1. 모듈 설치

npm i fs

참고사이트 : https://www.npmjs.com/package/fs

 

fs

This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it.. Latest version: 0.0.1-security, last pub

www.npmjs.com

 

 

 

2. 폴더 생성

'teamnova'라는 폴더 생성

임의의 폴더와 파일들을 생성해줍니다.

내용이 비어있어도 상관없습니다. 폴더인지 파일인지 구분만 할거기 때문입니다. 

 

 

 

3. 예제

const fs = require('fs'); 
const path = require('path'); 

files = fs.readdirSync(__dirname);  // 모든 파일 조회

files.forEach(file => { 
    console.log(file);
    statsObj = fs.statSync(file); 
    console.log("Path is file:", statsObj.isFile()); // 파일이면 true
    console.log("Path is directory:", statsObj.isDirectory());  // 폴더면 true 
})

 

 

 

4. 결과

파일인지 폴더인지 구분하는 함수사용

 

이상으로 해당 파일이 일반 파일인지 폴더인지 구분하는 방법에 대해 살펴봤습니다.