특정 디렉토리 하위의 모든 폴더 및 파일 리스트를 가져오는 방법을 소개합니다.
1. fs.readdir()를 이용한 방법
fs.readdir(path, callback)
는 path의 하위 파일 및 디렉토리 리스트들을 비동기적으로 가져옵니다. 결과는 callback으로 전달됩니다.
const fs = require('fs');
fs.readdir("/var", (err, files) => {
if (err) {
throw err;
}
files.forEach(file => {
console.log(file);
});
});
Output:
cache
crash
lib
local
lock
log
mail
metrics
opt
run
snap
spool
test.txt
tmp
www
실제로 /var
의 하위 폴더 및 파일들을 확인하면 위의 내용과 일치합니다.
$ ls /var
cache crash lib local lock log mail metrics opt run snap spool test.txt tmp www
1.1 file type 함께 출력
fs.readdir(path, options, callback)
는 option도 인자로 받는데, withFileTypes: true
를 추가하면 파일, 디렉토리 같은 파일 타입을 함께 전달해줍니다.
const fs = require('fs');
fs.readdir("/var/", { withFileTypes: true }, (err, files) => {
if (err) {
throw err;
}
files.forEach(file => {
console.log(file);
});
});
Output:
Dirent { name: 'cache', [Symbol(type)]: 2 }
Dirent { name: 'crash', [Symbol(type)]: 2 }
Dirent { name: 'lib', [Symbol(type)]: 2 }
Dirent { name: 'local', [Symbol(type)]: 2 }
Dirent { name: 'lock', [Symbol(type)]: 3 }
Dirent { name: 'log', [Symbol(type)]: 2 }
Dirent { name: 'mail', [Symbol(type)]: 2 }
Dirent { name: 'metrics', [Symbol(type)]: 2 }
Dirent { name: 'opt', [Symbol(type)]: 2 }
Dirent { name: 'run', [Symbol(type)]: 3 }
Dirent { name: 'snap', [Symbol(type)]: 2 }
Dirent { name: 'spool', [Symbol(type)]: 2 }
Dirent { name: 'test.txt', [Symbol(type)]: 1 }
Dirent { name: 'tmp', [Symbol(type)]: 2 }
Dirent { name: 'www', [Symbol(type)]: 2 }
2. fs.readdirSync()을 이용한 방법
fs.readdirSync(path)
는 path 하위의 파일과 폴더 리스트를 동기적인 방법으로 가져옵니다.
const fs = require('fs');
const files = fs.readdirSync("/var/");
files.forEach(file => {
console.log(file);
});
위와 동일하게 fs.readdirSync(path, option)
로 option을 전달하여 파일 타입을 출력할 수 있습니다.
const fs = require('fs');
const files = fs.readdirSync("/var/", { withFileTypes: true });
files.forEach(file => {
console.log(file);
});
Loading script...
Related Posts
- JavaScript - slice()로 배열 자르기, 나누기
- Node.js - 파일에 특정 문자열이 포함되어있는지 확인
- Node.js - 특정 패턴과 일치하는 모든 파일 찾기
- Node.js - 디렉토리의 파일 리스트 가져오기
- Node.js - 파일, 디렉토리(하위 파일) 삭제
- Node.js - 파일 이름 변경
- JavaScript - switch 조건문
- JavaScript - 배열의 특정 요소 찾기, Index 찾기
- JavaScript - 특정 값으로 배열 채우기, Array.fill()
- JavaScript - null, undefined 체크 방법
- JavaScript - 배열을 객체로 변환, 4가지 방법
- JavaScript - 이번 달(특정 달)의 1일, 마지막 일 구하기
- JavaScript - 배열의 특정 요소 삭제 방법
- JavaScript - 배열에 특정 값이 포함되어있는지 확인
- JavaScript - Date에 시간(일/시/분/초) 더하기
- JavaScript - 변수가 배열인지 확인, 3가지 방법
- JavaScript - 변수가 문자열인지 확인
- JavaScript - 문자열이 숫자인지 확인
- JavaScript - Map의 key를 배열로 변환
- JavaScript - Map의 value를 배열로 변환
- JavaScript - Map 요소 삭제 방법