通过node遍历某个目录从而生成md文件展示层级目录结构

28 阅读1分钟

image.png

const fs = require('fs');
const path = require('path');

function generateMarkdownForDirectory(dirPath, depth = 0, markdown = '') {
  const files = fs.readdirSync(dirPath);

  files.forEach((file) => {
    const filePath = path.join(dirPath, file);
    const stats = fs.statSync(filePath);

    if (stats.isDirectory()) {
      markdown += `${'  '.repeat(depth)}- ${file}\n`;
      markdown = generateMarkdownForDirectory(filePath, depth + 1, markdown);
    } else {
      markdown += `${'  '.repeat(depth)}- [${file}](${filePath})\n`;
    }
  });

  return markdown;
}

const directoryPath = 'D:\\frontedProject\\scriptcatList';
const markdownContent = generateMarkdownForDirectory(directoryPath);

// fs.writeFileSync('directoryStructure.md', markdownContent);

fs.writeFileSync('scriptList.md', markdownContent);