From 293e3fbb8495a497e515ac7afcb9be537daa0a28 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Sat, 11 May 2019 07:49:27 +0100 Subject: [PATCH] no need to generate the class dynamically --- index.js | 57 +++++++++++++++++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/index.js b/index.js index cf952c4..f519c87 100644 --- a/index.js +++ b/index.js @@ -10,40 +10,47 @@ const defaultOptions = { } } -function bufferStream (limit, options = {}) { - options = Object.assign({}, defaultOptions, options) - let emitted = 0 +class BufferStream extends Readable { + constructor (limit, options) { + super() - class BufferStream extends Readable { - _read () { - const nextLength = emitted + options.chunkSize - let nextChunkSize = options.chunkSize + this.limit = limit + this.options = options + this.emitted = 0 + } - if (nextLength > limit) { - nextChunkSize = limit - emitted - } + _read () { + const nextLength = this.emitted + this.options.chunkSize + let nextChunkSize = this.options.chunkSize - options.generator(nextChunkSize, (err, bytes) => { - if (err) { - this.emit('error', err) - return - } + if (nextLength > this.limit) { + nextChunkSize = this.limit - this.emitted + } - bytes = bytes.slice(0, nextChunkSize) + this.options.generator(nextChunkSize, (err, bytes) => { + if (err) { + this.emit('error', err) + return + } - emitted += nextChunkSize + bytes = bytes.slice(0, nextChunkSize) - this.push(bytes) + this.emitted += nextChunkSize - if (nextLength > limit) { - // we've finished, end the stream - this.push(null) - } - }) - } + this.push(bytes) + + if (nextLength > this.limit) { + // we've finished, end the stream + this.push(null) + } + }) } +} + +const bufferStream = (limit, options = {}) => { + options = Object.assign({}, defaultOptions, options) - return new BufferStream() + return new BufferStream(limit, options) } module.exports = bufferStream