gcl
Version:
码农村nodejs类库,完成解决回调陷阱,配置框架,IOC框架,统一多DB访问框架,可扩展日志框架和io/db/net/thread/pool 克隆表达式,加解密算法等等一系列基础类库和算法的实现
44 lines • 1.6 kB
JavaScript
import S from 'stream';
import { isArray, isBoolean } from 'util';
import V from '../common/tool';
/**
* 内存流提供Stream写入与读取的一切方法,但是仅仅限于写入居多的toArray方法
*/
export const ArrayStream = class extends S.Duplex {
constructor(size = 0,buffer = 1024 * 16) {
super({ allowHalfOpen: true, readableObjectMode: true, writableObjectMode: true,highWaterMark:buffer });
const _ = this;
_.max = size;
_.buf = [];
_.buffersize = buffer;
}
_read(length) {
const _ = this;
if (_.buf.length) {
// console.log('_read',length)
_.push(Buffer.from(_.buf.splice(0, length ? length : _.buffersize)));
} else _.push(null);
}
_write(chunk, encoding, callback) {
const _ = this;
let _buf = _.buf;
_.buf = _buf.concat(chunk.toJSON ? chunk.toJSON().data : chunk);
_buf = null;
callback((_.max > 0 && _.buf.length > _.max) ? new Error('limit out of size:' + _.max) : null);
}
_writev(chunks, callback) {
const _ = this;
V.each(chunks, v => {
let _buf = _.buf;
_.buf = _buf.concat(v.chunk.toJSON ? v.chunk.toJSON().data : v.chunk);
_buf.splice(0, _buf.length);
_buf = null;
return false;
}, true).then(() => callback((_.max > 0 && _.buf.length > _.max) ? new Error('limit out of size:' + _.max) : null));
};
toArray() {
let _ = this;
return _.buf.splice(0, _.buf.length);
};
}
export default { ArrayStream }