How to check if a path is a directory in Node.js?

December 19, 2020 - 3 min read

To check if a path is a directory in Node.js, we can use the stat() (asynchronous execution) function or the statSync() (synchronous execution) function from the fs (filesystem) module and then use the isDirectory() method returned from the stats object.

// Check if path is a directory
fs.statSync("./reports").isDirectory();

For example, Let's say we have a directory called reports so that the path to the directory looks like this,

// require fs module
const fs = require("fs");

// a path
const path = "./reports";

Using the fs.stat() function (Asynchronous Way)

Let's check if the path is a directory using the fs.stat() function.

The fs.stat() function needs 2 arguments:

  • The first argument is the path to check
  • The second argument is an error first callback function that will get executed after reading all the stats about the path.

It can be done like this,

// require fs module
const fs = require("fs");

// a path
const path = "./reports";

// check if path is directory using
// the fs.stat() function
fs.stat(path, (error, stats) => {
  // incase of error
  if (error) {
    console.error(error);
    return;
  }

  console.log(stats);

  /*
    Stats {
        dev: 3822,
        mode: 16877,
        nlink: 1,
        uid: 1000,
        gid: 1000,
        ..
        ..
    }
    */
});

In the stats object we can use the isDirectory() method to check to see if the path is a directory or not like this,

// require fs module
const fs = require("fs");

// a path
const path = "./reports";

// check if path is directory using
// the fs.stat() function
fs.stat(path, (error, stats) => {
  // incase of error
  if (error) {
    console.error(error);
    return;
  }

  // check if path is a directory
  console.log(stats.isDirectory()); // true
});

See this example live in repl.it.

Using the fs.statSync() function (Synchronous Way)

Let's check if the path is a directory using the fs.statSync() function.

The fs.statSync() function needs a path to check as the first argument.

It can be done like this,

// require fs module
const fs = require("fs");

// a path
const path = "./reports";

// check if path is directory using
// the fs.statSync() function
const stats = fs.statSync(path);

The function returns an object containing all the stats about the path.

In the stats object we can use the isDirectory() method to check to see if the path is a directory or not like this,

// require fs module
const fs = require("fs");

// a path
const path = "./reports";

// check if path is directory using
// the fs.statSync() function
const stats = fs.statSync(path);

// check if directory
console.log(stats.isDirectory()); // true

See this example live in repl.it.

Feel free to share if you found this useful 😃.