Delete a file in Node using unlink() and unlinkSync() method

In this short post, we will learn how to delete/remove a file from the filesystem in Node JS.

In Node, you can delete a file using the unlink() and unlinkSync() method that is provided by the fs module. This function helps to delete a file from the local filesystem using Node Js.

Let’s see how both functions work using an example.

The fs.unlink() method is an asynchronous method that does not block the execution of the node event loop while removing the file from the local filesystem.

The syntax of deleting a file using fs.unlink() is:

fs.unlink(filePath, callbackFunction)

Once the file is deleted the callback function is executed to check for errors during the removal of the file.

Example:

const fs = require('fs')

const filePath = './myfile.txt'

fs.unlink(filePath, (err) => {
  if (err) {
    console.error(err)
    return';
  }
    //file deleted
})

You have to include the fs mode first and then use pass the path of the file and the callback function as an argument.

If there is any error in deleting the file it will show the error in the console and return the function.

We can also delete a file synchronously from the local filesystem using fs.unlinkSync() function in Node. This method will block the execution of the node even loop until the file is removed.

The syntax of unlinkSync() method is

fs.unlinkSync(filePath)

Now let’s see an example to delete a file.

const fs = require('fs')

const filePath = './myfile.txt'

try {
  fs.unlinkSync(filePath)
  //file deleted from the system
} catch(err) {
  console.error(err)
}

Here, we have used the fs.unlinkSync() method inside a try..catch statement. If there is an error during the removal of the file then we can catch the error and display it in the console.

Scroll to Top