Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
Why is the array length zero?

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);
     }

 }

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda