How to delete uploaded file in Sailsjs (req.file)?

1.3k Views Asked by At

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?

1

There are 1 best solutions below

3
hlozancic On BEST ANSWER

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