SHIN
Node.js 실전 팁 20선
20편Node.js 10+부터 fs/promises를 사용하면 async/await로 파일 작업을 깔끔하게 처리할 수 있습니다.
import { readFile, writeFile, appendFile } from 'fs/promises';
// 파일 읽기
const content = await readFile('config.json', 'utf-8');
const config = JSON.parse(content);
// 파일 쓰기 (덮어쓰기)
await writeFile('output.json', JSON.stringify(data, null, 2), 'utf-8');
// 파일에 내용 추가
await appendFile('app.log', `[${new Date().toISOString()}] 로그 내용\n`);import { access, constants } from 'fs/promises';
async function fileExists(path) {
try {
await access(path, constants.F_OK);
return true;
} catch {
return false;
}
}
// 읽기 가능 여부 확인
async function isReadable(path) {
try {
await access(path, constants.R_OK);
return true;
} catch {
return false;
}
}import { mkdir, readdir, rm, stat } from 'fs/promises';
import path from 'path';
// 중첩 디렉토리 생성
await mkdir('logs/2024/01', { recursive: true });
// 디렉토리 내 파일 목록
const files = await readdir('./src', { withFileTypes: true });
const jsFiles = files
.filter((f) => f.isFile() && f.name.endsWith('.js'))
.map((f) => f.name);
// 파일 정보
const info = await stat('package.json');
console.log(`크기: ${info.size} bytes`);
console.log(`수정일: ${info.mtime}`);
// 디렉토리 삭제 (재귀)
await rm('./dist', { recursive: true, force: true });import { copyFile, rename, cp } from 'fs/promises';
// 파일 복사
await copyFile('source.txt', 'dest.txt');
// 파일 이동 (rename)
await rename('old-name.txt', 'new-name.txt');
// 디렉토리 전체 복사 (Node.js 16.7+)
await cp('./src', './backup', { recursive: true });import { watch } from 'fs/promises';
async function watchConfig(filePath) {
const watcher = watch(filePath);
console.log(`${filePath} 감시 시작`);
for await (const event of watcher) {
console.log(`이벤트: ${event.eventType}, 파일: ${event.filename}`);
// 설정 파일 변경 시 재로드 등
}
}async function loadConfig(filePath, defaults = {}) {
try {
const raw = await readFile(filePath, 'utf-8');
return { ...defaults, ...JSON.parse(raw) };
} catch (err) {
if (err.code === 'ENOENT') return defaults; // 파일 없으면 기본값
throw err; // 다른 에러는 전파
}
}