Created
September 3, 2018 10:55
-
-
Save roccomuso/d4af2be33e08abcdf546f304286254ee to your computer and use it in GitHub Desktop.
Stream a buffer in loop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {isBuffer} = Buffer | |
const {Readable} = require('readable-stream') | |
class StreamLoop extends Readable { | |
constructor(data, options = {}) { | |
if (!isBuffer(data)) throw new Error('data must be a Buffer') | |
super(options) // Readable opts | |
this.data = data | |
this.length = data.byteLength | |
this.offset = 0 | |
this.lap = 0 | |
} | |
_read (size) { | |
let chunk = this.data.slice(this.offset, this.offset + size) | |
if ((this.offset + size) >= this.length) { | |
let rest = (this.offset + size) - this.length | |
chunk = Buffer.concat([chunk, this.data.slice(0, rest)]) | |
this.emit('lap', ++this.lap) | |
this.offset = rest | |
} else { | |
this.offset += size | |
} | |
this.push(chunk) | |
} | |
} | |
module.exports = StreamLoop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: