Node.js: How to check if folder is empty or not with out uploading list of files

后端 未结 6 1974
日久生厌
日久生厌 2021-02-12 18:59

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

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-12 19:39

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

提交回复
热议问题