Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a file after download it using nodejs

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             
};
like image 307
Ragnar Avatar asked Jan 14 '15 19:01

Ragnar


1 Answers

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);
like image 93
mscdex Avatar answered Sep 17 '22 16:09

mscdex