nodejs
Node.js로 서버나 CLI 도구를 개발할 때, 파일 시스템을 비동기적으로 제어하는 것은 흔한 일입니다. 하지만 콜백 지옥(callback hell)은 여전히 개발자의 숙제였었습니다. 이 문제를 해결하기 위해 Node.js에서는
이 글에서는
Node.js v10 이상부터 사용할 수 있으며, 기존
const fs = require('fs').promises;
const fs = require('fs').promises;
async function readFileExample() {
const data = await fs.readFile('./example.txt', 'utf-8');
console.log(data);
}
readFileExample();
async function writeFileExample() {
await fs.writeFile('./output.txt', 'Hello, World!', 'utf-8');
console.log('파일 쓰기 완료');
}
writeFileExample();
async function checkFileExists(path) {
try {
await fs.access(path);
console.log('파일이 존재합니다.');
} catch {
console.log('파일이 존재하지 않습니다.');
}
}
checkFileExists('./some.txt');
async function deleteFile() {
try {
await fs.unlink('./output.txt');
console.log('파일 삭제됨');
} catch (err) {
console.error('삭제 실패:', err);
}
}
deleteFile();
async function manageFolder() {
await fs.mkdir('./logs', { recursive: true });
console.log('디렉토리 생성 완료');
await fs.rmdir('./logs');
console.log('디렉토리 삭제 완료');
}
manageFolder();
* 참고: Node.js v16 이후부터는 fs.rm(path, { recursive: true })를 권장합니다.
async function listDirectory() {
const files = await fs.readdir('./');
console.log('현재 디렉토리 목록:', files);
}
listDirectory();
async function showStats() {
const stat = await fs.stat('./example.txt');
console.log('파일 크기:', stat.size);
console.log('마지막 수정:', stat.mtime);
}
showStats();
async function renameFile() {
await fs.rename('./example.txt', './renamed.txt');
console.log('파일 이름 변경 완료');
}
renameFile();
async function copyAndDelete() {
try {
const data = await fs.readFile('./original.txt', 'utf-8');
await fs.writeFile('./copy.txt', data);
await fs.unlink('./original.txt');
console.log('복사 후 원본 삭제 완료');
} catch (err) {
console.error('오류 발생:', err);
}
}
copyAndDelete();
요약하자면: