【问题标题】:Do not read directories after 3 level using node js3级后不要使用node js读取目录
【发布时间】:2021-07-02 22:45:06
【问题描述】:

有没有办法在特定点或3级树结构之后停止读取目录

例如

MainFolder
-ABC Folder
-DEF Folder
-GHI Folder
-image.png
-jkl.gif

当我点击 ABC 文件夹时,我的路径将如下所示 /MainFolder/ABC Folder 如果其中有任何其他文件夹或文件,那么它看起来像

/MainFolder/ABC Folder
-PQR Folder
-STU Folder
-abc.pdf
-xyz.txt

点击 PQR 文件夹然后它看起来像这样

/MainFolder/ABC Folder/PQR Folder
-DFC Folder
-HKJ Folder
-mnb.pdf
-xyz.txt

但不应读取 DFC 文件夹/HKJ 文件夹或 3 级树结构后存在的任何其他文件夹 输出:-

["MainFolder/image.png",
"MainFolder/jkl.gif",
"MainFolder/ABC Folder/abc.pdf",
"MainFolder/ABC Folder/xyz.txt",
"MainFolder/ABC Folder/PQR Folder/mnb.pdf",
"MainFolder/ABC Folder/PQR Folder/xyz.txt"]

我让它读取所有文件和子目录的代码,但我想停在 3level 目录

async function getAllFile(folderPath) {
  let files = await fs.readdir(folderPath);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stats = await fs.stat(filePath);
      if (stats.isDirectory()) {
        return getAllFile(filePath);
      } else if (stats.isFile()) return filePath;
    })
  );

  return files.reduce((all, folderContents) => all.concat(folderContents), []);
}

PS : 使用节点 10.16.3

【问题讨论】:

    标签: javascript node.js async-await promise callback


    【解决方案1】:

    这应该可以解决您的问题。我添加了深度参数,它基本上代表您要遍历的文件夹级别。对于您的文件树,您可以使用深度 2 调用此函数:getAllFile('./MainFolder/', 2),因为您想探索根目录(级别 1)和子文件夹(级别 2),而不是子文件夹中的文件夹(级别 3) .

    如果文件夹仍未探索,我也会返回 null,否则会导致 undefined 值。在返回之前,我会过滤掉这些 null 值。

    async function getAllFile(folderPath, depth) {
      depth -= 1;
      let files = await fs.readdir(folderPath);
      files = await Promise.all(
        files.map(async (file) => {
          const filePath = path.join(folderPath, file);
          const stats = await fs.stat(filePath);
          if (stats.isDirectory() && depth > 0) {
            return getAllFile(filePath, depth);
          } else if (stats.isFile()) return filePath;
          else return null;
        })
      );
      return files.reduce((all, folderContents) => all.concat(folderContents), []).filter(e => e != null);
    }
    

    【讨论】:

    • 它不工作@fravolt仍在读取所有文件夹
    • 根不计入深度。 (比如说)0 的深度不应该返回子文件夹的内容,而 1 的深度应该返回子文件夹,而不是子子文件夹。我更新了我的原始答案并包含了我可以运行的代码
    • @fravolt "请注意,对我来说 fs.readdir 和 fs.stat 函数不会返回,而是需要回调函数,但这可能是我的版本不匹配(我在节点 V12.18.3 上)。” - 您可以在 Node v12 上使用 require('fs').promises 来访问 fs 方法的承诺版本。
    • @fravolt 我试过你的代码,但我仍然得到目录但感谢你的帮助:-)
    • @Aakash 我刚刚提出了一个新的更好的解决方案。我自己用你的文件夹结构测试了这个,它似乎按预期工作。请让我知道它是否有效! :D
    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 2017-10-28
    • 2020-11-07
    • 2017-03-22
    • 2016-12-18
    • 1970-01-01
    • 2021-08-11
    • 2016-11-07
    相关资源
    最近更新 更多