const fs = require('fs') const { EventEmitter } = require('events') class MyFileReadStream extends EventEmitter { constructor (path, options = {}) { super() this.path = path this.flags = options.flags || 'r' this.mode = options.mode || 438 this.autoClose = options.autoClose || true this.start = options.start || 0 this.end = options.end this.hightWaterMark = options.hightWaterMark || 64*1024 this.openMethod() } openMethod () { console.log('openMethod') // 源生open方法来打开指定位置上的文件 fs.open(this.path,this.flags,this.mode,(err, fd)=>{ if (err) { this.emit('error', err) } this.fd = fd console.log(fd) this.emit('myOpen', fd) // 发布事件 }) } } const rs = new MyFileReadStream('test.txt') rs.on('myOpen', function(fd){ // 注册订阅事件 console.log('myOpen', 'fd') }) rs.on('error', (err=>{ console.log(err) }))