프로미스 기반 readFile 함수로 파일 읽기
이 단계에서는 프로미스 기반 readFileSync 함수를 사용하여 test-promisefy.json 파일을 읽는 방법을 배우게 됩니다.
index.js 파일에 다음 코드를 추가합니다:
fs.readFile(textPath, "utf8", (err, contrast) => {
const readFileSync = promisefy(fs.readFile);
readFileSync(textPath, "utf8")
.then((res) => {
console.log(res === contrast); // The result here is expected: true, i.e. the promise returns the same content as the previous read.
})
.catch((err) => {});
});
이 코드는 파일 경로와 인코딩을 사용하여 readFileSync 함수를 호출한 다음, then 및 catch 메서드를 사용하여 프로미스 해결 및 거부를 처리합니다.
- 이제
index.js 파일은 다음과 같아야 합니다:
const fs = require("fs");
const path = require("path");
const textPath = path.join(__dirname, "/test-promisefy.json");
fs.readFile(textPath, "utf8", (err, contrast) => {
const readFileSync = promisefy(fs.readFile);
readFileSync(textPath, "utf8")
.then((res) => {
console.log(res === contrast); // The result here is expected: true, i.e. the promise returns the same content as the previous read.
})
.catch((err) => {});
});
const promisefy = (fn) => {
return (textPath, type) => {
return new Promise((resolve, reject) => {
fn(textPath, type, (err, contrast) => {
if (err) {
reject(err);
} else {
resolve(contrast);
}
});
});
};
};
module.exports = promisefy;
- 터미널에서
index.js 파일을 실행합니다:
node index
true 출력을 볼 수 있습니다. 이는 프로미스 기반 readFile 함수가 원래 콜백 기반 readFile 함수와 동일한 내용을 반환했음을 의미합니다.
축하합니다! readFile 함수를 성공적으로 프로미스화하고 프로미스 기반 버전을 사용하여 파일을 읽었습니다.