Skip to content

Instantly share code, notes, and snippets.

@ivoputzer
Created October 28, 2016 10:36
Show Gist options
  • Save ivoputzer/f11f9110ef5a43591cffd4a146675ad9 to your computer and use it in GitHub Desktop.
Save ivoputzer/f11f9110ef5a43591cffd4a146675ad9 to your computer and use it in GitHub Desktop.
stream-data to buffer and string
const {Readable, PassThrough} = require('stream')
const {createReadStream} = require('fs')
const {ok, equal} = require('assert')
describe('toString', function(){
it('converts a fs-stream to buffer', done => {
let stream = createReadStream('/dev/null')
toString(stream, function(string){
equal(string, String())
ok(~ done())
})
})
it('converts a readable-stream to buffer', done => {
let stream = new Readable()
stream._read = Function.prototype // stubbed
toBuffer(stream, function(buffer){
equal(buffer, 'foo')
ok(~ done())
})
stream.push('foo')
stream.push(null)
})
it('converts a passthrough-stream to buffer', done => {
let stream = new PassThrough()
toBuffer(stream, function(buffer){
equal(buffer, 'foo')
ok(~ done())
})
stream.write('foo')
stream.end()
})
})
function toBuffer(stream, fn, chunks = []){
stream.on('data', chunk => chunks.push(chunk))
stream.on('end', data => fn(Buffer.concat(chunks)))
}
function toString(stream, fn){
return toBuffer(stream, (buffer) => fn(buffer.toString()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment