Skip to content

Instantly share code, notes, and snippets.

@roccomuso
Created September 3, 2018 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roccomuso/d4af2be33e08abcdf546f304286254ee to your computer and use it in GitHub Desktop.
Save roccomuso/d4af2be33e08abcdf546f304286254ee to your computer and use it in GitHub Desktop.
Stream a buffer in loop.
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
@roccomuso
Copy link
Author

Usage example:

let video = require('fs').readFileSync('/home/user/video.mp4')
let loop = new StreamLoop(video)

loop.on('lap', i => {
  console.error(`Lap ${i}`)
})

loop.pipe(process.stdout)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment