最近好久都没写博客了,主要是没干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))
})