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

featured Image

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.

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *