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);
Related videos on Youtube
![Ragnar](https://i.stack.imgur.com/NU1jN.jpg?s=256&g=1)
Comments
-
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 almost 8 yearsQix is an example of why people are leaving stack overflow
-
moncheery over 7 yearsfor 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 about 7 yearsQix, I google'd and got this question. I think we just divided by zero.
-
-
Cumulo Nimbus almost 6 yearsis 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