Open Silence-dream opened 1 year ago
const fs = require("fs"); const path = require("path"); // 递归遍历指定目录生成目录树 function generateDirectoryTree( directoryPath, ignoreDirectories = [], ignoreFiles = [], prefix = "", depth = Infinity ) { // 如果深度已经达到指定的层级,则不再继续遍历 if (depth === 0) { return ""; } // 获取该目录下所有的文件和子目录 const items = fs.readdirSync(directoryPath); // 遍历过程中用来记录目录树结构的字符串 let tree = ""; // 对于每个文件和子目录,执行如下操作 items.forEach((item, index) => { // 获取该项的完整路径,并判断它是文件还是子目录 const itemPath = path.join(directoryPath, item); const isDirectory = fs.statSync(itemPath).isDirectory(); // 如果该项是要忽略的文件夹或文件,则直接返回 if (ignoreDirectories.includes(item) || ignoreFiles.includes(item)) { return; } // 组装前缀字符串,用于输出目录结构 const prefixString = prefix + (index === items.length - 1 ? "└─ " : "├─ "); // 输出当前文件或目录的名称 tree += `${prefixString}${item}\n`; // 如果该项是子目录,则递归遍历它,并将生成的目录结构添加到当前目录结构中 if (isDirectory) { tree += generateDirectoryTree( itemPath, ignoreDirectories, ignoreFiles, prefix + (index === items.length - 1 ? " " : "│ "), depth - 1 ); } }); // 返回生成的整个目录树结构 return tree; } // 输出生成的目录树到指定文件中 function outputDirectoryTreeToFile(tree, outputPath) { fs.writeFileSync(outputPath, tree); } // 测试代码 let result = generateDirectoryTree( "./", ["node_modules", "dist", "docs-dist", ".dumi", ".ds_store", ".git", ".idea"], [".gitignore"], "", 3 ); outputDirectoryTreeToFile(result, "./tree.txt");