Converting a Buffer into a ReadableStream in Node.js

Masiar picture Masiar · Nov 5, 2012 · Viewed 86.3k times · Source

I'm fairly new to Buffers and ReadableStreams, so maybe this is a stupid question. I have a library that takes as input a ReadableStream, but my input is just a base64 format image. I could convert the data I have in a Buffer like so:

var img = new Buffer(img_string, 'base64');

But I have no idea how to convert it to a ReadableStream or convert the Buffer I obtained to a ReadableStream.

Is there a way to do this or am I trying to achieve the impossible?

Thanks.

Answer

Mr5o1 picture Mr5o1 · May 21, 2017

something like this...

import { Readable } from 'stream'

const buffer = new Buffer(img_string, 'base64')
const readable = new Readable()
readable._read = () => {} // _read is required but you can noop it
readable.push(buffer)
readable.push(null)

readable.pipe(consumer) // consume the stream

In the general course, a readable stream's _read function should collect data from the underlying source and push it incrementally ensuring you don't harvest a huge source into memory before it's needed.

In this case though you already have the source in memory, so _read is not required.

Pushing the whole buffer just wraps it in the readable stream api.