プロミスベースの 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); // ここの結果は期待通り: true、つまりプロミスは前回の読み取りと同じ内容を返します。
})
.catch((err) => {});
});
このコードは、ファイルパスとエンコーディングを使って readFileSync
関数を呼び出し、その後 then
と catch
メソッドを使って Promise の解決と拒否を処理します。
- このとき、あなたの
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); // ここの結果は期待通り: true、つまりプロミスは前回の読み取りと同じ内容を返します。
})
.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
関数をプロミスに変換し、プロミスベースのバージョンを使ってファイルを読み取りました。