Introduction

Do you need to check if a file exists in a filesystem using Node.js?

Node.js has an Fs core module that provides some built-in ways to check if a file exists. In this article, we'll go over the fs.existsSync() and fs.access() methods.

Let's get started!

Table of Contents

Method 1 - fs.existsSync()

The first method we'll cover is the fs.existsSync() method provided by the Fs core module.

This will test whether or not a given file path exists in the system the code is being run on. We'll need to pass a string of the file path to the function and it'll return a true or false value.

Here's what the code looks like:

    
      const fs = require("fs")

      const path = "./filename.txt"

      try {
        if (fs.existsSync(path)) {
          console.log("File exists.")
        } else {
          console.log("File does not exist.")
        }
      } catch(err) {
        console.error(err)
      }
    
  

Let's go over what we did in the code.

The first thing we did was require() the Fs core module. Since this is a core module and not an NPM package, we don't need to install anything.

Next, we created a path variable that holds the full path to the file we want to check for.

Since the fs.existsSync() method is synchronous, we created a try...catch statement to run the code inside of.

Inside the try section, we supply the fs.existsSync() with the path to our file and log a success or fail message depending on whether the file exists or not.

When you run the code, it will log either a "File exists." or "File does not exist" message.

Method 2 - fs.access()

The second method we'll cover is fs.access().

This method tests a user's permissions for a file or directory given a specific file path. And can also be used to check if a file exists.

Here's what the code looks like:

    
      const fs = require("fs")

      const path = "./filename.txt"

      fs.access(path, fs.F_OK, (err) => {
        if (err) {
          console.log("File does not exist.")
        } else {
          console.log("File exists.")
        }
      })
    
  

Let's cover what's going on in the code.

Like before, we require() the Fs core module and create a path variable that holds the path to the file we want to check.

Then, we use the fs.access() function and pass three parameters to it:

  • file path: this the full path to the file we are checking for existence.
  • mode: an optional integer that specifies the accessibility checks to be performed.
  • callback function: a function that is called with a possible error argument. If any of the accessibility checks fail, it will return an Error object.

When you run the code, it will log a success or failure message depending on whether or not the file exists.

Conclusion

There you have it! Now you know two different ways to check if a file exists using the Fs core module and it's two methods: fs.existsSync() and fs.access().

Thanks for reading and happy coding!