Delete a file after download it using nodejs

Ragnar picture Ragnar · Jan 14, 2015 · Viewed 9.7k times · Source

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             
};

Answer

mscdex picture mscdex · Jan 14, 2015

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);