不要使用节点js读取3级后的目录

Do not read directories after 3 level using node js

有什么方法可以在特定点或 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 Folder/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"]

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

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

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

如果文件夹仍未探索,我也会 return null,否则会导致 undefined 值。在 returning 之前,我过滤掉了这些 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);
}