0

In Sails.js, one could receive an uploaded file as such:

myControllerAction: function(req, res) {
  req.file('avatar', function(err, uploadedFiles) {
    // uploaded avatar image will be available here
    console.log(uploadedFiles[0]);
  }
}

Suppose I received a file, but it is not properly formatted the way I want. I would just reply with an error. One thing I would like to do is make sure that received file does not remain in the filesystem (i.e. if it exists somewhere, delete it). How can I ensure that?

nbkhope
  • 7,360
  • 4
  • 40
  • 58

1 Answers1

4

Just use node fs module to delete uploaded file.

const fs = require('fs');

fs.unlink(insertFilePathHere, function(err) {
  if (err) return console.log(err); // handle error as you wish

  // file deleted... continue your logic
});
hlozancic
  • 1,489
  • 18
  • 31
  • Read more here: https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback – hlozancic Jun 29 '17 at 09:07
  • Hey, thanks for the tip! I was wondering where the file was uploaded to. It goes to `/your/project/directory/.tmp/uploads/`. You can easily get the full path using **uploadedFiles[0].fd**. So, using what you suggested will do the job. – nbkhope Jun 29 '17 at 18:55
  • 2
    Don't forget to check skipper docs (https://github.com/balderdashy/skipper) to see how to change default upload directory using dirname and saveAs options if needed ;) – hlozancic Jun 29 '17 at 21:41