I'm using fs-extra library to delete some image files on post request in my node js app. every time I call /deleteproduct route everything works fine. my product is removed from database and fs-extra callback doesn't throw any error even though files are not removed! I don't know what is the reason. I think maybe I'm doing something wrong with async/await functions.
this is my code:
router.post('/deleteproduct', async (req, res) => {
try {
const id = req.body.id;
const deleteProduct = await prisma.product.findUnique({
where: { id: id }
});
const images = JSON.parse(deleteProduct.image);
for(let i = 0; i < images.length; i++) {
await fsExtra.remove(path.join(__dirname, `public/images/${images[i]}`), (err) => {
if (err) console.log(err);
});
console.log(images[i]);
}
await prisma.product.delete({
where: { id: id }
});
res.status(200).json({ msg: "Deleted product with id: " + id });
} catch (error) {
res.json({ msg: error });
}
});
EDIT: image files are inside images folder in public directory.
please comment if you need more info
directories image:
cpanel.js is deleting the files
There might be two problems here. First, your are not using correct path to reference your files correctly. Secondly, you are using await and callbacks at the same time. You can do something like this.
try {
const images = JSON.parse(deleteProduct.image);
const imageProm = [];
for(let i = 0; i < images.length; i++) {
imageProm.push(fsExtra.remove(path.join(__dirname, `public/images/${images[i]}`)
}
const result = await Promise.all(imageProm);
await prisma.product.delete({
where: { id: id }
});
}
catch (e) {console.log(e)}
If the above solution doesn't work why can't you use fs.unlink
a native method provided to work for such scenarios. Try using that.
Note: whenever you use async/await use try/catch block to catch errors.