Search code examples
node.jspathfs

how to determine whether the directory is empty directory with nodejs


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?


Solution

  • 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;
        });
    }