Node Modules 2 - fs (file system)

정형진·2022년 12월 24일
0

Node.js Basics

목록 보기
2/2

fs

file 동기와 비동기

fs 모듈 내의 함수들은 보통 아래와 같은 세 가지의 형태로 제공된다.

const fs = require('fs');

fs.renameSync('./file.txt', './file-new.txt'); // 파일명이 존재하지 않으면 crash 발생.

try {
	renameSync('./file.txt', './file-new.txt');
} catch (error) {
	console.error(error);
}

메소드 이름 뒤에 sync가 붙는 형태의 함수는 비동기 처리를 하지 않는 함수로서 오류가 발생할 가능성이 있을 때는 반드시 try, catch문으로 감싸주어야 한다. 일반적으로는 굳이 sync를 사용할 이유는 없다.

const fs = require('fs');

fs.rename('./file.txt', './file-new.txt', (error) => console.error(error));

그냥 rename은 비동기 함수로서 콜백 함수를 전달 받게 된다. 보통 에러 발생 시 실행될 함수를 작성한다.

const fs = require('fs');

fs.promises
  .rename("./file.txt", "./file-new.txt")
  .then(() => console.log("Done!"))
  .catch(console.error);

fs.promises 에 있는 함수들은 위처럼 promise 형태로 수행할 수 있는 함수들이다.

fs.promises

readFile

const fs = require("fs").promises;

fs.readFile("./text.txt")
  .then((data) => console.log(data)) // Buffer 형태로 반환.
  .catch(console.error);

fs.readFile("./text.txt", { encoding: 'utf8' })
  .then((data) => console.log(data)) // utf-8로 인코딩 되어 변환.
  .catch(console.error);

readFile은 그냥 실행하면 Buffer 형태로 반환하는데, 두 번째 인자로 option을 전달할 수 있다. 예시처럼 인코딩 형태를 명시해주면 원하는 인코딩 형태로 파일을 읽을 수 있다.

writeFile, appendFile

const fs = require("fs").promises;

fs.writeFile("./file.txt", "Hello!").catch(console.error);
fs.appendFile("./file.txt", "\nHello from here too!").catch(console.error);

writeFile은 첫 번째 인자에 있는 경로의 파일을 두 번째 인자로 덮어쓰게 된다. 반환 형태는 void라서 따로 출력되는 것은 없으나 then을 통해서 실행된 이후에 비동기적으로 실행하고 싶은 구문을 작성할 수도 있다. 만약 덮어쓰는 게 아니라 파일 뒤에 추가로 붙여넣고 싶다면 appendFile을 쓰면 된다.

copyFile

const fs = require("fs").promises;

fs.copyFile("./file.txt", "./file2.txt").catch(console.error);
fs.mkdir('folder').catch(console.error);
fs.readdir('./')..then(console.log).catch(console.error);

copyFile은 첫 번째 인자로 전달받은 파일을 두 번째 인자의 디렉토리로 복사한다. mkdir은 요청한 명칭의 폴더를 만들어준다. readdir은 요청한 디렉토리 내의 모든 파일과 폴더의 이름을 배열 형태로 출력한다.

profile
사실 나도 잘 모름

0개의 댓글