nodejs
Node.js로 서버나 유틸성 스크립트를 만들다 보면 디렉토리 내부의 파일 목록을 가져와야 하는 경우가 종종 있습니다. 이미지 처리 파이프라인을 만든다거나, 정적 파일을 자동으로 읽어서 클라이언트에 전달하는 식의 작업이 그렇죠.
이럴 때 많이 사용하는 함수가 바로
사용법은 매우 단순하지만, 콜백 기반이기 때문에 기본 구조는 이렇게 생겼습니다:
const fs = require('fs');
fs.readdir('./uploads', (err, files) => {
if (err) {
console.error('에러 발생:', err);
return;
}
console.log('파일 목록:', files);
});
위 예제는
const path = require('path');
fs.readdir('./uploads', (err, files) => {
if (err) return;
files.forEach((file) => {
const fullPath = path.join('./uploads', file);
fs.stat(fullPath, (err, stats) => {
if (err) return;
if (stats.isFile()) console.log('파일:', file);
if (stats.isDirectory()) console.log('폴더:', file);
});
});
});
Node.js v10 이후부터는
const fs = require('fs').promises;
const path = require('path');
async function listFiles() {
try {
const files = await fs.readdir('./uploads');
for (const file of files) {
const fullPath = path.join('./uploads', file);
const stat = await fs.stat(fullPath);
if (stat.isFile()) console.log('파일:', file);
if (stat.isDirectory()) console.log('폴더:', file);
}
} catch (err) {
console.error('에러 발생:', err);
}
}
listFiles();
요약하자면:
파일 목록을 다뤄야 하는 모든 Node.js 개발자에게는 꼭 알아야 할 필수 함수 중 하나입니다.