node.js remove file

Solution 1:

I think you want to use fs.unlink.

More info on fs can be found here.

Solution 2:

You can call fs.unlink(path, callback) for Asynchronous unlink(2) or fs.unlinkSync(path) for Synchronous unlink(2).
Where path is file-path which you want to remove.

For example we want to remove discovery.docx file from c:/book directory. So my file-path is c:/book/discovery.docx. So code for removing that file will be,

var fs = require('fs');
var filePath = 'c:/book/discovery.docx'; 
fs.unlinkSync(filePath);

Solution 3:

If you want to check file before delete whether it exist or not. So, use fs.stat or fs.statSync (Synchronous) instead of fs.exists. Because according to the latest node.js documentation, fs.exists now deprecated.

For example:-

 fs.stat('./server/upload/my.csv', function (err, stats) {
   console.log(stats);//here we got all information of file in stats variable

   if (err) {
       return console.error(err);
   }

   fs.unlink('./server/upload/my.csv',function(err){
        if(err) return console.log(err);
        console.log('file deleted successfully');
   });  
});