最近好久都沒寫博客了,主要是沒幹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))
- })