Last active
November 17, 2015 05:54
-
-
Save cmmartin/f5bb0f4598b7b51441d4 to your computer and use it in GitHub Desktop.
Convert a stream to a Buffer in Node.js
This file contains 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
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