Node.js — Check If a Directory Is Empty

You want a solid and convenient experience when working with the file system in Node.js. The file system comes with its own challenges, like space limitations and access restrictions.

Typically you also need to ensure a given state. For example, you want to delete all files from a given directory and ensure that the directory is empty.

This tutorial shows you how to determine whether a given directory is empty.

Node.js Series Overview

Detect If a Directory is Empty

A typical approach to determine whether a directory is empty is to count the files in that directory. Counting files requires JavaScript to load all files into memory and then comparing if the file count is greater than zero.

What we suggest instead is using an iterator allowing you to open a directory for a scanning process. That means you’re reading each file one by one instead of everything upfront.

Using the directory iterator to detect if a directory is empty requires you to read only one file. The iterator returns null on its first read representing an empty directory.

Here’s a Node.js snippet allowing you to check if a directory is empty:

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

/**
 * Determine whether the given `path` points to an empty directory.
 *
 * @returns {Boolean}
 */
function isEmptyDir(path) {  
    try {
      const dirent = await Fs.opendir(path)
      const value = await dirent.read()
      await dirent.close()

      return value === null
    } catch (error) {
      return false
    }
}

The try/catch block is helpful in case the path doesn’t exist or isn’t a directory. For existing directories, you’re checking whether the returned value from reading a file is null. The directory is empty in such cases.

Use the @supercharge/fs Package

I’m the maintainer of the @supercharge/fs package providing convenient file system utilities. The @supercharge/fs package comes with this handy isEmptyDir(path) method determining whether a the path points to an empty directory:

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

const isEmptyDir = await Fs.isEmptyDir('./storage/cache')  
// false

const isEmptyDir = await Fs.isEmptyDir('./storage/empty-dir')  
// true

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.