0

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}`);
                }
classydraught
  • 352
  • 1
  • 4
  • 13
  • @Klaycon Actually no, I haven't undefined but actually I am getting 0. when I am logging it I can clearly see the value is incrementing. – classydraught Jun 24 '20 at 18:17
  • 3
    The reason is the same. Asynchronous code is scheduled to run at some undetermined point in the future. Your `.forEach(async item => {` schedules each callback to run some undetermined point in the future, and then your code continues. Looking closer, this is specifically a gotcha with forEach and async code. See here: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Klaycon Jun 24 '20 at 18:23
  • @Klaycon Thank's that helped!! – classydraught Jun 24 '20 at 18:52

0 Answers0