Nodejs 遍历目录树 组建内存tree

本文介绍了一个Node.js后端项目的需求,通过遍历硬盘上的所有文件,计算文件的hash值,并利用Visitor模式和Tree模型实现这一功能。Node.js的Stream在处理大量文件时表现出优越的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近好久都没写博客了,主要是没干iOS了,现在在写后端,用的Nodejs,加上最早java的功底,以及对javascript的了解,目前没什么问题+

说说最近的项目中遇到的一个小需求。

把硬盘所有文件爬一遍并计算hash,不过话说回来。nodejs的Stream是真的好用。

为什么有这个需求,不讲了。实现原理也就是visitor Pattern. tree model

以下是代码。

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

const uuid = require('uuid')

class Node {
  constructor(name, type, parent){
    this.name = name
    this.parent = parent
    this.child = []
    this.type = type
    this.id = uuid.v4()
  }
}

//这就是一个 visitor
function visit(dir, dirContext, func, done) {
  fs.readdir(dir, (err, entries) => {
    if (err || entries.length === 0) return done()
    let count = entries.length
    entries.forEach(entry => {
      func(dir, dirContext, entry, (entryContext) => {
        if (entryContext) {
          visit(path.join(dir, entry), entryContext, func, () => {
            count--
            if (count === 0) done()
          })
        }
        else {
          count --
          if (count === 0) done()
        }
      })
    })
  })
}

let count = 0
let map = new Map()
let u = false
const clean = (dir, dirContext, entry, callback) => {
  console.log(count++)
  let fpath = path.join(dir, entry)

  fs.lstat(fpath, (err, stats) => {
    if(err) return callback()
    if(stats.isFile()){
      let node = new Node(entry, 'file')
      map.set(node.id, node)
      dirContext.child.push(node)
      callback() 
    }else if(stats.isDirectory()){
      let node = new Node(entry, 'folder')
      map.set(node.id, node)
      dirContext.child.push(node)
      callback(node)
    }else{
      let node = new Node(entry, 'unknown')
      u = node.id
      map.set(node.id, node)
      dirContext.child.push(node)
      callback(node)
    }
  })
}

let n = new Node('usr', 'folder')
map.set(n.id, n)

visit('/usr', n, clean, ()=> {
  fs.writeFile('test.json', JSON.stringify(n, null, ' '))
  console.log('----------------------------',map.size)
  console.log(map.get(n.id))
})


具体实现就是这些了。里面没有包括hashworker的代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值