Node.js: How to check if folder is empty or not wi

2020-06-08 04:22发布

问题:

I am using Node.js.

I want to check if folder is empty or not? One option is to use fs.readdir but it loads whole bunch of files into an array. I have more than 10000 files in the folder. Loading files name is useless just to check if folder is empty or not. So looking for alternate solution.

回答1:

How about using nodes native fs module http://nodejs.org/api/fs.html#fs_fs_readdir_path_callback. It's readdir and readdirSync functions provide you with an array of all the included file names (excluding . and ..). If the length is 0 then your directory is empty.



回答2:

This is an ugly hack but I'll throw it out there anyway. You could just call fs.rmdir on the directory. If the callback returns an error which contains code: 'ENOTEMPTY', it was not empty. If it succeeds then you can call fs.mkdir and replace it. This solution probably only makes sense if your script was the one which created the directory in the first place, has the proper permissions, etc.



回答3:

You can execute any *nix shell command from within NodeJS by using exec(). So for this you can use the good old 'ls -A ${folder} | wc -l' command (which lists all files/directories contained within ${folder} hiding the entries for the current directory (.) and parent directory (..) from the output which you want to exclude from the count, and counting their number).

For example in case ./tmp contains no files/directories below will show 'Directory ./tmp is empty.'. Otherwise, it will show the number of files/directories that it contains.

var dir = './tmp';
exec( 'ls -A ' + dir + ' | wc -l', function (error, stdout, stderr) {
    if( !error ){
        var numberOfFilesAsString = stdout.trim();
        if( numberOfFilesAsString === '0' ){
            console.log( 'Directory ' + dir + ' is empty.' );
        }
        else {
            console.log( 'Directory ' + dir + ' contains ' + numberOfFilesAsString + ' files/directories.' );
        }
    }
    else {
        throw error;
    }
});


回答4:

What about globbing? ie, exists myDir/*. It is not supported out of box by node (TOW v0.10.15), but bunch of modules will do that for you, like minimatch



回答5:

Just like to add that there's a node module extfs which can be used to check if a directory is empty using the function isEmpty() as shown by the code snippet below:

var fs = require('extfs');

fs.isEmpty('/home/myFolder', function (empty) {
  console.log(empty);
});

Check out the link for documentation regarding the synchronous version of this function.



回答6:

Duplicate from my answer in 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