18

我正在使用Node.js.

我想检查文件夹是否为空?一种选择是使用fs.readdir,但它将整个文件加载到一个数组中。我的文件夹中有超过 10000 个文件。加载文件名只是为了检查文件夹是否为空。所以寻找替代解决方案。

4

6 回答 6

13

如何使用节点本机fs模块http://nodejs.org/api/fs.html#fs_fs_readdir_path_callback。它readdirreaddirSync函数为您提供所有包含文件名的数组(不包括.and ..)。如果长度是0那么你的目录是空的。

于 2014-11-06T11:16:34.737 回答
12

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.

于 2013-01-29T08:24:03.757 回答
6

您可以使用 exec() 从 NodeJS 中执行任何 *nix shell 命令。因此,为此您可以使用旧的 'ls -A ${folder} | wc -l' 命令(列出 ${folder} 中包含的所有文件/目录,将当前目录 (.) 和父目录 (..) 的条目隐藏在要从计数中排除的输出中,并计算它们的数字)。

例如,如果 ./tmp 不包含以下文件/目录,则将显示“目录 ./tmp 为空。”。否则,它将显示它包含的文件/目录的数量。

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;
    }
});
于 2013-10-05T04:03:18.570 回答
2

从我的答案中复制如何使用nodejs确定目录是否为空目录

有可能使用opendir为目录创建迭代器的方法调用。

这将消除读取所有文件的需要并避免潜在的内存和时间开销

    import {promises as fsp} from "fs"
    const dirIter = await fsp.opendir(_folderPath);
    const {value,done} = await dirIter[Symbol.asyncIterator]().next();
    await dirIter.close()

done 值会告诉您目录是否为空

于 2020-02-03T10:33:59.790 回答
0

就像补充一点,有一个节点模块extfs可用于使用函数isEmpty()检查目录是否为空,如下面的代码片段所示:

var fs = require('extfs');

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

查看有关此功能的同步版本的文档链接。

于 2014-08-24T22:12:55.613 回答
0

通配符呢?即,exists myDir/*。节点不支持开箱即用(TOW v0.10.15),但是一堆模块会为你做到这一点,比如minimatch

于 2013-08-06T19:43:41.320 回答