let fs = require('fs');
let event = require('events');
// 会把多个写入 进行排队调用
class CreateWriteStream extend event {
constructor(path,options={}){
super();
this.path = path;
this.flags = options.flags||'w';
this.autoClose= options.autoClose||true;
this.encoding = options.encoding||'utf8';
this.highWaterMark = options.highWaterMark||64*1024;
this.start = options.start||0;
// 用来存储多个调用
this.cache =[];
// 写入的个数
this.len =0;
this.pos = this.start;
// 是否需要触发 drain 事件
this.needDrain = false;
this.writing = false;
this.open();
}
open(){
fs.open(this.path,this.flags,(err,fd)=>{
if(err){
this.emit('error',err)
}
this.fd = fd;
this.emit('open', fd);
})
}
write(chunk, encoding = this.encoding, callback){
if(typeOf this.fd !=number){
this.once('open',()=>this.write(chunk, encoding, callback));
}
chunk = Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);
this.len + =chunk.length;
let flag = this.len > this.highWaterMark;
if (flag) {
this.needDrain = true;
}
// 第一次会写入
if(this.writing){
this.cache.push({
chunk,
encoding,
callback
})
}else{
this.write=true;
this._write(chunk,encoding,()=>clearBuffer())
}
return !flag;
}
_write(chunk,encoding,callback){
fs.write(this.fd,chunk,0,chunk.length,this.pos,(err,written)=>{
this.pos +=written;
this.len -=written;
callback();
})
}
clearBuffer(){
//获取第一个元素的值 并且删除
let obj =this.cache.shift();
if(obj){
this._write(obj.chunk,obj.encoding,()=>this.clearBuffer());
}else{
// 缓存区空了
if(this.needDrain){ //应该写入文件中
this.writing = false;
this.needDrain = false;
this.emit('drain')
}
}
}
}
createWriteStream
最新推荐文章于 2024-01-20 23:30:58 发布