Aditya Pranav
Aditya Pranav

Reputation: 47

Nodejs File get deleted before sending response (res.send)

Here the problem is File get deleted from the server before sending a response to the client and display error as no image on this path.

 // Here some code 
 res.status(200).sendFile(path.join(__dirname, "../../image", `/${response.id}.png`));

   // Delete image from server
    fs.unlink(imagePath, function (err) {
         if (err) throw err;
         console.log('File deleted!');
     })

Upvotes: 0

Views: 1457

Answers (1)

jfriend00
jfriend00

Reputation: 707406

You will need to monitor the callback to res.sendFile() so you know when the sending is actually done before you can safely delete your file.

res.sendFile() is asynchronous so it returns before the job is done, thus you were deleting the file before res.sendFile() was done. Use the callback to know when it's actually done.

   let fname = path.join(__dirname, "../../image", `/${response.id}.png`);
   res.status(200).sendFile(fname, err => {
      if (err) {
          console.log(err);
          res.sendStatus(500);
      }
      fs.unlink(fname, function(err) => {
         // log any error
         if (err) {
             console.log(err);
         }
      });
   });

Note: When you pass a callback to res.sendFile() you have to manually handle an error condition and send an error response, retry, send alternative content, etc... to send some appropriate response.

I'm also wondering why you're sending one filename and attempting to delete a different one. Wouldn't it make sense to use the same local variable for the filename you're sending and the one you're deleting?

Upvotes: 4

Related Questions