I have a mern app. I want to delete file with fs.unlink function. But I have a problem. My array length zero. Actually I know the problem but I can't solve it. Javascript first assigns a value to the post.image object and then executes the fs.readdir function. How can I solve this problem?
const updatePost = async (req, res) => {
const obj = req.body;
try{
await Posts.findById(obj._id).then((post) => {
const filePath = path.join(path.resolve() + "/public/images/")
console.log("obj.image", obj.image);
// output => obj.image undefined
console.log("post.image.length", post.image.length);
// output => 1
if (obj.image === undefined) {
fs.readdir(filePath, (err, files) => {
for (let c = 0; c < files.length; c++) {
const file = files[c];
console.log(post.image.length);
// output => 0 and the loop is not working.
for (let d = 0; d < post.image.length; d++) {
const postFile = post.image[d].originalname;
if (file === postFile) {
fs.unlink(`${filePath}${file}`, (err) => {
err && console.log(err);
console.log("remove same image");
});
}
}
}
});
}
post.image = obj.image === undefined ? [] : obj.image;
}
}
catch(err){
console.log(err);
}
}