파일 입출력을 지원하는 모듈이다.
공식 문서에 따르면, 비동기 방식을 사용하는 API와, 콜백과 동기 방식을 사용하는 API 두가지 모두를 제공한다.
https://nodejs.org/api/fs.html#fs_promise_example
공식문서에서 친절하게 CommonJS, ES Module 두가지 방법 모두 fs 모듈을 불러오는 방법을 알려준다.
비동기 방식을 사용해보았다. 비동기 방식으로 제공하는 API는 promise를 반환하므로 promise.then().catch()를 사용하거나 async/await을 사용할 수 있다.
import fs from "fs/promises";
fs.readFile("./readme.txt").then((data) => console.log(data));
try {
const data = await fs.readFile("./readme.txt");
console.log(data);
} catch (err) {
console.log(err);
}
console에 data를 찍어보니 버퍼가 나온다.
공식 문서에는 이렇게 적혀있다.
If no encoding is specified (using options.encoding), the data is returned as a object. Otherwise, the data will be a string.
readFile 메서드에 두번째 옵션으로 인코딩 타입을 넣어줬다.
try {
const data = await fs.readFile("./readme.txt", "utf8");
console.log(data);
} catch (err) {
console.log(err);
}
제대로 출력이 된다. 또는 toString() 메서드를 사용하는 방법도 있다.
try {
const result = await fs.writeFile("./writeFile.txt", "이건 파일 쓰기");
console.log(result);
} catch (err) {
console.log(err);
}
파일 쓰기의 경우, promise resolve될 경우 특별한 리턴값이 없다.
심심해서 객체도 한번 넣어봤다.
const obj = {
name: "yeoneseo",
age: 32,
gender: "man",
};
try {
const result = await fs.writeFile("./writeFile.txt", obj);
console.log(result);
} catch (err) {
console.log(err);
}
에러가 발생한다. 공식 문서에는 이렇게 나와 있다.
data can be a string, a buffer, an AsyncIterable or Iterable object, or an object with an own toString function property.
그래서 객체를 문자열로 바꿔 writeFile 메서드를 사용했다.
try {
const result = await fs.writeFile("./writeFile.txt", JSON.stringify(obj));
console.log(result);
} catch (err) {
console.log(err);
}
잘 찍힌다.