Delete file in Node.js using node fs

In Node.js to delete a file you have to use fs module of node whether you are using any framework like Express or Koa etc. Node FS provides two function to delete files from disk, unlink(path, callback) and unlinkSync(path). 

unlink(path, callback) is asynchronous and provides callback functionality to inform file deletion successful or failed.

unlinkSync(path) is synchronous and throws an error if file deletion is failed.

Let see one by one example of both and know how to use it.

unlink(path, callback):

const fs = require('fs'); // get instance of fs module

const file = '/var/www/website/uploads/sample.jpg';
fs.unlink(file, function (err) {
    if (err){
        console.log("Unable to delete file!", err.message);
    }else{
        // if no error, file has been deleted
        console.log('File has been deleted!');
    }
});

 

unlinkSync(path):

const fs = require('fs'); // get instance of fs module

const file = '/var/www/website/uploads/sample.jpg';
try{
    fs.unlinkSync(file);
    // if no error, file has been deleted
    console.log('File has been deleted!');
}catch(err){
   console.log("Unable to delete file!", err.message);
}

 

in ES6 or later you can use as below:

import { unlinkSync } from 'fs'; // get instance of fs.unlinkSync module

const file = '/var/www/website/uploads/sample.jpg';
try{
    unlinkSync(file);  // use await unlinkSync(file); if code inside async function. 
    // if no error, file has been deleted
    console.log('File has been deleted!');
}catch(err){
   console.log("Unable to delete file!", err.message);
}


Keywords: