I am trying to read all files in folder, check if it has featured: true prop, increase the counter if it does and then throw error if there is more than 1 such file. But for some reason, my code doesn’t wait and simply jumps to last section, this is the output
this should be last
Inside item, looking for featured prop
Inside item, looking for featured prop
My code:
const fs = require('fs');
const findInDir = require('./utils/findInDir');
(async () => {
const dir = './public/page-data/blog';
const fileRegex = /.*/;
const allFiles = findInDir(dir, fileRegex);
let result = 0;
await allFiles.map(file => {
fs.readFile(file, 'utf8', (err, data) => {
const obj = JSON.parse(data);
if (obj.result.pageContext.featured === true) {
console.log('Inside item, looking for featured prop');
result += 1;
}
});
});
console.log('this should be last');
if (result > 1) {
throw new Error('There are multiple featured blog posts, please fix.');
}
})();
Need some help understanding what am I doing wrong.
>Solution :
You need to use the non-callback version of fs.readFile in order to actually await reading the file. Also using .map does not make a lot of sense as you’re not actually mapping something, so simply use a for .. of loop:
for (const file of allFiles){
try {
const data = await fs.promises.readFile(file);
// ...
} catch(err) {
// handle error
}
}
console.log('this should be last');