Skip to content

Commit

Permalink
no need to generate the class dynamically
Browse files Browse the repository at this point in the history
  • Loading branch information
achingbrain committed May 11, 2019
1 parent 33bdb02 commit 293e3fb
Showing 1 changed file with 32 additions and 25 deletions.
57 changes: 32 additions & 25 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 293e3fb

Please sign in to comment.