Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!