You have to return a promise and since fs.readFile
uses callbacks you will have to wrap it in one.
In your code you did return a promise but you didn’t await
anything nor could you have since there is nothing to be awaited. Your console log logged the data because it was called async and your function returned nothing as the return
statement happened in the async thread.
The below code should work
const fs = require("fs");
const fileName = "./utils/readme.txt";
const getMoviesData = () => {
return new Promise((resolve, reject) => {
fs.readFile(fileName, "utf8", (err, data) => {
if (err) {
reject(err);
}
console.log(data);
resolve(data);
});
});
};
module.exports = getMoviesData;
As @jfriend00 pointed out, you can also use the promised based readFile
function that comes in with node >= 10.
const { readFile } = require("fs/promises");
const fileName = "./utils/readme.txt";
const getMoviesData = () => {
return readFile(fileName, "utf8");
};
module.exports = getMoviesData;
CLICK HERE to find out more related problems solutions.