23
votes

I have searched the Nodejs Doc,But don't find relative API.

So I write the following code to determine whether the directory is empty directory.

var fs = require('fs');

function isEmptyDir(dirnane){
    try{
        fs.rmdirSync(dirname)
    }
    catch(err){
        return false;
    }
    fs.mkdirSync(dirname);
    return true
}

QUESTION:it look like some troublesome,there is better way to do it with nodejs?

3

3 Answers

40
votes

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;
    });
}
13
votes

simple sync function like you were trying for:

const fs = require('fs');

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

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