how to determine whether the directory is empty directory with nodejs

There is the possibility of using the opendir method call that creates an iterator for the directory.

This will remove the need to read all the files and avoid the potential memory & time overhead

import {promises as fsp} from "fs"
const dirIter = await fsp.opendir(_folderPath);
const {value,done} = await dirIter[Symbol.asyncIterator]().next();
await dirIter.close()

The done value would tell you if the directory is empty


I guess I'm wondering why you don't just list the files in the directory and see if you get any files back?

fs.readdir(dirname, function(err, files) {
    if (err) {
       // some sort of error
    } else {
       if (!files.length) {
           // directory appears to be empty
       }
    }
});

You could, of course, make a synchronous version of this too.

This, of course, doesn't guarantee that there's nothing in the directory, but it does mean there are no public files that you have permission to see there.


Here's a promise version in a function form for newer versions of nodejs:

function isDirEmpty(dirname) {
    return fs.promises.readdir(dirname).then(files => {
        return files.length === 0;
    });
}

simple sync function like you were trying for:

const fs = require('fs');

function isEmpty(path) {
    return fs.readdirSync(path).length === 0;
}

Tags:

Path

Node.Js

Fs