递归获取目录NodejS中的所有文件

新手上路,请多包涵

我的功能有点问题。我想获取许多目录中的所有文件。目前,我可以检索传入参数的文件中的文件。我想检索作为参数传递的文件夹中每个文件夹的 html 文件。我将解释如果我输入参数“test”我在“test”中检索文件,但我想检索“test / 1 / *. Html”,“test / 2 / . / .html”:

 var srcpath2 = path.join('.', 'diapo', result);
function getDirectories(srcpath2) {
                return fs.readdirSync(srcpath2).filter(function (file) {
                    return fs.statSync(path.join(srcpath2, file)).isDirectory();
                });
            }

结果:[1,2,3]

谢谢 !

原文由 user6285277 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 453
2 个回答

看起来 glob npm 包 会帮助你。以下是如何使用它的示例:

文件层次结构:

 test
├── one.html
└── test-nested
    └── two.html

JS代码:

 const glob = require("glob");

var getDirectories = function (src, callback) {
  glob(src + '/**/*', callback);
};
getDirectories('test', function (err, res) {
  if (err) {
    console.log('Error', err);
  } else {
    console.log(res);
  }
});

显示:

 [ 'test/one.html',
  'test/test-nested',
  'test/test-nested/two.html' ]

原文由 Paul Mougel 发布,翻译遵循 CC BY-SA 4.0 许可协议

我见过很多很长的答案,这有点浪费内存空间。有些还使用像 glob 这样的包,但如果你不想依赖任何包,这是我的解决方案。

 const Path = require("path");
const FS   = require("fs");
let Files  = [];

function ThroughDirectory(Directory) {
    FS.readdirSync(Directory).forEach(File => {
        const Absolute = Path.join(Directory, File);
        if (FS.statSync(Absolute).isDirectory()) return ThroughDirectory(Absolute);
        else return Files.push(Absolute);
    });
}

ThroughDirectory("./input/directory/");

这是不言自明的。有一个输入目录,它会遍历它。如果其中一项也是一个目录,则通过它等等。如果是文件,则将绝对路径添加到数组。

希望这有帮助:]

原文由 Smally 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题