Tengo una aplicación Mern. Quiero eliminar el archivo con la función fs.unlink. Pero tengo un problema. Mi matriz de longitud cero. En realidad conozco el problema pero no puedo resolverlo. Javascript primero asigna un valor al objeto post.image y luego ejecuta la función fs.readdir. ¿Como puedó resolver esté problema?
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); } }