nodejs遍历文件夹获取文件

const { promisify } = require("util");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");

async function run(basePath, deep = false) {
  let currentDeep = deep;
  if (deep !== false) {
    if (deep <= 0) {
      return;
    } else {
      currentDeep -= 1;
    }
  }
  const files = await promisify(fs.readdir)(basePath);
  let data = [];
  for (const file of files) {
    const filePath = path.join(basePath, file);
    if ((await promisify(fs.stat)(filePath)).isDirectory()) {
      const dirData = await run(filePath, currentDeep);
      //   console.log(dirData)
      if (dirData) {
        data = [...data, ...dirData];
      }
    } else {
      //   console.log(filePath);
      let item = data.find((v) => v.dir === basePath);
      if (!item) {
        item = {
          dir: basePath,
          files: [filePath],
        };
        data.push(item);
      } else {
        item.files.push(filePath);
      }
    }
  }
  return data;
}

const basePath = path.dirname(__dirname);
const htmlBase = path.join(basePath, "show");

run(basePath, 2).then((r) => {
  if (!fs.existsSync(htmlBase)) {
    fs.mkdirSync(htmlBase);
  }

  let indexStr = "<ol>";
  for (const item of r) {
    const md5 = crypto.createHash("md5");
    const htmlName = md5.update(item.dir).digest("hex") + ".html";
    console.log(htmlName);
    indexStr += `<li><a href="${htmlName}">${item.dir}(${item.files.length})</a></li>`;

    let imgStr = '<div id="con">';
    for (const file of item.files) {
      imgStr += `<img src="../${file
        .split("\\")
        .slice(-2)
        .join("/")}" alt="${file}" />`;
    }
    imgStr += "</div>";
    const htmlPath = path.join(htmlBase, htmlName).replace(/\\/g, "/");
    fs.writeFileSync(htmlPath, imgStr);
  }
  indexStr += "</ol>";

  const indexHtml = path.join(htmlBase, "index.html");
  fs.writeFileSync(indexHtml, indexStr);
  console.log(indexHtml);
});
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注