Are you looking for a way to delete or remove a file from a directory using Node.js? This article will show you how to get that done.

Node.js has a built-in way to do this with their File System (Fs) core module, which has both a fs.unlink() and fs.unlinkSync() method to remove a file.

The synchronous fs.unlinkSync() version will stop your code and wait until the file has been removed or an error occurred. And the asynchronous version fs.unlink() will not block your code and return a callback function when the file is removed.

We'll show you how to use both examples.

First, let's go over the fs.unlink() approach:

      const fs = require("fs")

      const pathToFile = "your-file.png"

      fs.unlink(pathToFile, function(err) {
        if (err) {
          throw err
        } else {
          console.log("Successfully deleted the file.")

Let's break down each part of the code:

  1. First, we import the Fs module and hold it in the fs variable.
  2. Next, we get the path to our file and hold it in a pathToFile variable.
  3. Then, we use the fs.unlink() function. We pass the file path to the function and it returns a callback.
  4. Inside the callback function, we do some error handling and then, if successful, we console.log() a success message.

And if you look in your directory, you should see the file in question removed.

Next, let's go over the synchronous fs.unlinkSync() method:

      const fs = require("fs")

      const pathToFile = "your-file.png"

      try {
        console.log("Successfully deleted the file.")
      } catch(err) {
        throw err

Similar to the previous example, we require the Fs module and then get the path to the file.

But then we use a try...catch statement. In the try section, we pass the pathToFile variable to the fs.unlinkSync() function and log a success message when the file is removed. And we use the catch section to throw any errors that occur.

When you look in your directory, the file will be removed.


Hopefully, this article was helpful in your coding endeavors.

Thanks for reading and happy coding!