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?
To check whether a directory is empty or not os. listdir() method is used. os. listdir() method of os module is used to get the list of all the files and directories in the specified directory.
Check if a File is Empty with Node. The easiest way to check is to stream the data within the file and check its length. If there are 0 bytes in the file, or rather, if the length of the data is equal to 0 , the file is empty: router.
js? To check if a path is a directory in Node. js, we can use the stat() (asynchronous execution) function or the statSync() (synchronous execution) function from the fs (filesystem) module and then use the isDirectory() method returned from the stats object.
To remove all files from a directory, first you need to list all files in the directory using fs. readdir , then you can use fs. unlink to remove each file. Also fs.
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;
});
}
simple sync function like you were trying for:
const fs = require('fs');
function isEmpty(path) {
return fs.readdirSync(path).length === 0;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With