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