Node核心模块

2019-06-24  本文已影响0人  我叫Aliya但是被占用了

buffer

无需引用,node内置

util

let util = require('util')
function A () { }
A.prototype.fn = () => {}
function B () { }
// B.prototype.__proto__ = A.prototype
// Object.setPrototypeOf(B.prototype, A.prototype)
// B.prototype = Object.create(A.prototype)
util.inherits(B, A)
console.log(new B().fn)
let fs = require('fs')
let readFilePromisify = util.promisify(fs.readFile)
readFilePromisify('./aa.txt', 'utf8').then(data => {}, err => {})

let fs = require('fs').promisify   // 还可以这样

events

const EventEmitter = require('events');
function myEmitter () {
  
}
util.inherits(myEmitter, EventEmitter)

let me = new myEmitter()

me.on('newListener', type => {
  console.log('newListener', type)
})

me.on('order1', msg => console.log('order1', msg))
me.emit('order1', 'haha')
me.once('once', msg => console.log('once', msg))
me.emit('once', 'onceonce')
me.emit('once', 'onceonce')

let fn = msg => console.log('order2', msg)
me.on('order2', fn)
me.emit('order2', 'off event')
me.off('order2', fn)
me.emit('order2', 'off event')

自己来实现一个,它要有:

function myEvent () {
  this.eventList = new Map()
}
myEvent.prototype.on = function (type, fn) {
  if (this.eventList.get(type)) 
    this.eventList.get(type).add(fn)
  else 
    this.eventList.set(type, new Set([fn]))
  if (type != 'newListener') {
    this.emit('newListener', type)
  }
} 
myEvent.prototype.emit = function (type, arg) {
  this.eventList.get(type) && this.eventList.get(type).forEach(fn => {
    if (fn.onceEvent) fn.onceEvent(arg)   // 执行once事件
    else fn(arg)
  });
}
myEvent.prototype.off = function (type, fn) {
  this.eventList.get(type) && this.eventList.get(type).delete(fn)
}
myEvent.prototype.once = function (type, fn) {
  fn.onceEvent = (arg) => {
    this.off(type, fn)
    fn(arg)
  }
  this.on(type, fn)
}

module.exports = myEvent

FS

// 异步目录删除 广度遍历
let fs = require('fs')
let path = require('path')
let next = count => fn => --count == 0 && fn()
let DirDeepDel = function (dir, callback) {
  fs.stat(dir, (err, stats) => {
    if (stats.isFile()) {
        return setTimeout(() => fs.unlink(dir, callback), 30)  // 当前路径是文件,直接删除
    }
    fs.readdir(dir, (err, files) => {
      if (files.length == 0) {
        return setTimeout(() => fs.rmdir(dir, callback), 3000) // 当前路径下为空,直接删除
      }
      let nextfn = next(files.length)
      files.forEach(file => { 
        DirDeepDel(path.join(dir, file), err => {
          if (!err) nextfn(() => fs.rmdir(dir, callback))
        })
      })
    })
  })
}
// 预期效果
DirDeepDel('./1', () => {})
上一篇 下一篇

猜你喜欢

热点阅读