Created
October 28, 2016 10:36
-
-
Save ivoputzer/f11f9110ef5a43591cffd4a146675ad9 to your computer and use it in GitHub Desktop.
stream-data to buffer and string
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 {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