I want to save the total count of image files in my mongoDB model. So I have used readdirSync() method and then iterating through each item, then checking if the item is file or not. If not I am just deleting it but if it is then I am checking again if it is image or not. There by incrementing a variable(totalFiles) if it is an image or I am simply unlinking it, if the file is not an image. When I am not doing the last filtering(Checking whether its image or not) then things are going as usual but when I am doing so the totalFiles are always being saved as 0. I know its because of async code but can't understand where things are exactly going wrong.
async () => {
var totalFiles = 0;
fs.readdirSync(`./static/${batchName}`, { withFileTypes: true })
.forEach(async item => {
if (item.isFile())
{
const data = await FileType.fromFile(`./static/${batchName}/${item.name}`)
if (data.mime === 'image/png' || data.mime === 'image/jpeg')
{
console.log(data.mime);
totalFiles++; console.log(totalFiles);
}
else
fs.unlinkSync(`./static/${batchName}/${item.name}`);
}
else rimraf.sync(`./static/${batchName}/${item.name}`)
})
const batch = new Batch({
_id: new mongoose.Types.ObjectId(),
batchName: batchName,
question: question,
pathtoBatch: `/static/${batchName}/`,
adminId: req.UserData.userId,
totalFiles: totalFiles
})
batch
.save()
.then((result) => {
res.status(201).json({ message: "File uploaded and extracted", result: result });
}).catch((err) => {
res.status(500).json({
result: err,
message: "Batch creation failed",
});
});
fs.unlinkSync(`./static/${name}`);
}