← coderrocketfuel.com

Check if a Directory Exists in Node.js

How do you check if a directory exists in a filesystem using Node.js?

Conveniently, Node.js has a built-in core module named Fs that has both an fs.access() and fs.existsSync() method to check for the existence of a directory or folder.

In this article, we'll show you how to use both in your code.

Let's get started!

Table of Contents

Method 1 - fs.access()

The first method we'll go over is the fs.access() function. This function takes a directory path as an argument and is usually used to test a user's permission for a file or directory. But, if the given path isn't found, the function will return an error.

Therefore, we can detect if a directory exists by seeing if the fs.access() function returns an error or not.

Here's an example of what the code would look like:

const fs = require("fs")

fs.access("./directory-name", function(error) {
  if (error) {
    console.log("Directory does not exist.")
  } else {
    console.log("Directory exists.")
  }
})

The first thing we do is import the fs module. Since this is built into Node.js, we don't need to install any NPM packages.

Then, we use the fs.access() function and pass a directory path to it as an argument. And we also pass a callback function as an additional parameter that returns an error if one exists.

If an error exists, that means the file doesn't exist. So, we use an if...else statement inside the fs.access() function that logs a different message depending on whether the file exists or not.

We'll go over one more method in the next section.

Method 2 - fs.existsSync()

As the name suggests, the fs.existsSync() function tests whether or not a given path exists in the filesystem.

The synchronous function takes a path as the sole argument.

Here's what the code looks like:

const fs = require("fs")

try {
  if (fs.existsSync("./directory-name")) {
    console.log("Directory exists.")
  } else {
    console.log("Directory does not exist.")
  }
} catch(e) {
  console.log("An error occurred.")
}

Since fs.existsSync() is synchronous, we create a try...catch method to wrap the code in to catch any errors.

Inside the try...catch, we use an if...else statement where we use the fs.existsSync() function to check if the given path to the directory exists.

When you run the code, a message will be logged indicating whether or not the directory exists.