我搜索过Nodejs Doc,但是找不到相关的API。
所以我编写以下代码来确定目录是否为空目录。
var fs = require('fs');
function isEmptyDir(dirnane){
try{
fs.rmdirSync(dirname)
}
catch(err){
return false;
}
fs.mkdirSync(dirname);
return true
}
问题:看起来有些麻烦,有更好的方法可以使用nodejs吗?
答案 0 :(得分:15)
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.
答案 1 :(得分:8)
简单的同步功能,就像您尝试的那样:
const fs = require('fs');
function isEmpty(path) {
return fs.readdirSync(path).length === 0;
}
答案 2 :(得分:3)
可以使用为目录创建迭代器的opendir
方法调用。
这将消除读取所有文件的需要,并避免潜在的内存和时间开销
import {promises as fsp} from "fs"
const dirIter = await fsp.opendir(_folderPath);
const {value,done} = await dirIter[Symbol.asyncIterator]().next();
await dirIter.close()
完成值将告诉您目录是否为空