Node.js — Check If a Path Is a Directory

You may want to determine whether a given path is a directory when working with the file system in Node.js. Node.js comes with the fs core module allowing you to interact with the local hard disk.

This tutorial shows you how to combine existing fs methods to determine whether a given path points to a directory.

Node.js Series Overview

Determine Whether a File Path Is a Directory

Node.js doesn’t expose a first-party isDirectory method on the fs module. You must build it yourself with the existing low-level APIs.

Yet, Node.js provides you the needed helpers to compose an isDirectory(path) method using the fs core module. Here’s how you can build a helper method:

const { promises: Fs } = require('fs')

 * Determine whether a directory exists at the given `path`.
 * @param {String} path
 * @returns {Boolean}
async function isDirectory(path) {  
  const stats = await Fs.stat(path)

  return stats.isDirectory()

await isDirectory('./node_modules')  
// true

await isDirectory('./package.json')  
// false

Use the @supercharge/filesystem Package

I’m the maintainer of the @supercharge/filesystem package providing async file system methods. This package exposes an isDirectory(path) method determining whether the given path points to a directory:

const Fs = require('@supercharge/filesystem')

await Fs.isDirectory('./node_modules')  
// true

await Fs.isDirectory('./package.json')  
// false


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.