16

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             
};
Ragnar
  • 4,393
  • 1
  • 27
  • 40
  • `fs.unlink(fileName, callBack);` – Ding Jan 14 '15 at 19:45
  • @Qix I have googled it, that's why I posted the question. – Ragnar Jan 14 '15 at 19:54
  • @Qix Yes, but that search doesn't have the answer I need, if you want I can vote down all your questions and answers... so try to help instead of vote down. – Ragnar Jan 14 '15 at 20:00
  • @Ragnar that is called [serial downvoting](http://meta.stackexchange.com/questions/28756/what-can-i-do-if-im-the-victim-of-serial-downvoting) and is dealt with automatically by the system. Secondly, the answer to your questions is all over Google. In the future, spend a little more time searching and save a little more time in return. – Qix - MONICA WAS MISTREATED Jan 14 '15 at 20:03
  • 7
    Qix is an example of why people are leaving stack overflow – Freedom_Ben Aug 11 '16 at 18:03
  • 3
    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 – moncheery Jan 24 '17 at 11:12
  • 1
    Qix, I google'd and got this question. I think we just divided by zero. – Yoshiyahu Jun 09 '17 at 20:56

1 Answers1

26

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);
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • 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 – Cumulo Nimbus Sep 19 '18 at 21:41