Skip to content

Instantly share code, notes, and snippets.

@cmmartin
Last active November 17, 2015 05:54
Show Gist options
  • Save cmmartin/f5bb0f4598b7b51441d4 to your computer and use it in GitHub Desktop.
Save cmmartin/f5bb0f4598b7b51441d4 to your computer and use it in GitHub Desktop.
Convert a stream to a Buffer in Node.js
import { Writable } from 'stream'
/**
* Create a Buffer from a stream (warning: loads all chunks into memory)
* Usage: myStream.pipe(new BufferStream(buffer => {}, err => {}))
*/
export default class BufferStream extends Writable {
data = []
constructor(onComplete, onError) {
super()
this.on('finish', () => onComplete(Buffer.concat(this.data)))
this.on('error', onError)
}
_write(chunk, encoding, next) {
this.data.push(chunk)
next()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment