Delete a file after download it using nodejs

11,946

You can call fs.unlink() on the finish event of res.

Or you could use the end event of the file stream:

var file = fs.createReadStream(fileName);
file.on('end', function() {
  fs.unlink(fileName, function() {
    // file deleted
  });
});
file.pipe(res);
Share:
11,946

Related videos on Youtube

Ragnar
Author by

Ragnar

SOreadytohelp

Updated on June 14, 2022

Comments

  • Ragnar
    Ragnar about 2 years

    I'm using Node.js and I need to delete a file after user download it. Is there any way to call a callback method after pipe process ends, or any event for that purpose?

    exports.downloadZipFile = function(req, res){
        var fileName = req.params['fileName'];
        res.attachment(fileName);
        fs.createReadStream(fileName).pipe(res); 
    
        //delete file after download             
    };
    
    • Freedom_Ben
      Freedom_Ben almost 8 years
      Qix is an example of why people are leaving stack overflow
    • moncheery
      moncheery over 7 years
      for the record i didnt find the answer by googling but i did find this question which has helped me. perhaps if i already knew the answer i'd know what to google for. thanks for asking Ragnar
    • Yoshiyahu
      Yoshiyahu about 7 years
      Qix, I google'd and got this question. I think we just divided by zero.
  • Cumulo Nimbus
    Cumulo Nimbus almost 6 years
    is there an equivalent way to do this with Koa? ctx.body = fs.createReadStream(filename) is what I was doing before, but i'd like to delete the file on 'end' using your method