Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete file after using response.download() in node.js?

I'm working on an app which has a server that downloads files to the client's device using response.download(). (I'm using node.js, express, and fs) Once these files are downloaded, they are just taking up space, so I've tried calling fs.unlinksync after the download to get rid of them. No such luck, though: I just get the following error: NOENT: No such file or directory.

Here is the relevant server-side code:

app.get("/file", function(request, response) {
  var filename = request.query.f;
  var filePath = "public/" + filename
  response.download(filePath);
//this is where I've tried putting fs.unlink
});

Any help would be greatly appreciated. Thanks!

like image 297
TheDeveloperNextDoor Avatar asked Dec 06 '22 09:12

TheDeveloperNextDoor


1 Answers

response.download has a callback function, you can delete your file after download as below

response.download(filePath, yourFileName, function(err) {
  if (err) {
    console.log(err); // Check error if you want
  }
  fs.unlink(yourFilePath, function(){
      console.log("File was deleted") // Callback
  });

  // fs.unlinkSync(yourFilePath) // If you don't need callback
});
like image 76
Ahmet Zeybek Avatar answered Dec 11 '22 09:12

Ahmet Zeybek