createWriteStream

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')
            }
        }
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值