命令 nodejs_nodejs 实现tree命令

fbc8d2ce12cc6bd1b4758b7950891025.png

实现步骤

  1. 先进行一层目录的输出
  2. 找到随着目录层级变化的量 归纳前缀
  3. 找出递归结束的点,即使终结递归。

实现效果哦

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
}

思路++

细节++

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值