![fbc8d2ce12cc6bd1b4758b7950891025.png](https://img-blog.csdnimg.cn/img_convert/fbc8d2ce12cc6bd1b4758b7950891025.png)
实现步骤
- 先进行一层目录的输出
- 找到随着目录层级变化的量 归纳前缀
- 找出递归结束的点,即使终结递归。
实现效果哦
![39acda2f67409ebe2f9da46c4030a5a1.png](https://img-blog.csdnimg.cn/img_convert/39acda2f67409ebe2f9da46c4030a5a1.png)
const fs = require('fs')
const path = require('path')
//模拟tree的方式打印出目录结构
/**
*
* @param {文件目录} filePath
* @param {一次最大深度遍历,目录层级的前缀,随着深度递增} deep
* @param {深层目录最大遍历层} maxDeep
*/
function getDirectoryTree(filePath, deep, maxDeep){
//结果
let result = 'n'
//文件深度
let currentDeep = 0
function load(filePath, deep, maxDeep) {
let prefix = new Array(deep + 1).join('| ').trim()
//获取当前目录信息
let dirs = []
let files = []
let pathChild = fs.readdirSync(filePath)
pathChild.forEach((item) => {
let childPath = path.join(filePath, item)
let stat = fs.statSync(childPath)
if (stat.isDirectory()) {
if (!(['node_modules', '.git'].indexOf(item) >= 0)) {
dirs.push(item)
}
} else {
files.push(item)
}
})
//分别进行处理
dirs.forEach((item) => {
result += `${prefix}-- ${item}/nn`
//再对目录进行处理
if (currentDeep < maxDeep) {
load(path.join(filePath, item), deep + 1)
currentDeep++
} else {
currentDeep = 0
}
})
files.forEach((item) => {
result += `${prefix}-- ${item}nn`
})
}
load(filePath, deep, maxDeep)
return result
}
思路++
细节++