Converting a Buffer into a ReadableStream in Node.js

Javascriptnode.jsStreamBuffer

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

For nodejs 10.17.0 and up:

const { Readable } = require('stream');

const stream = Readable.from(myBuffer.toString());

Solution 2 - Javascript

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.

Solution 3 - Javascript

Node Stream Buffer is obviously designed for use in testing; the inability to avoid a delay makes it a poor choice for production use.

Gabriel Llamas suggests streamifier in this answer: https://stackoverflow.com/questions/16038705/how-a-wrap-a-buffer-as-a-stream2-readable-stream#16039177

Solution 4 - Javascript

You can create a ReadableStream using [Node Stream Buffers][1] like so:

// Initialize stream
var myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
  frequency: 10,      // in milliseconds.
  chunkSize: 2048     // in bytes.
}); 

// With a buffer
myReadableStreamBuffer.put(aBuffer);

// Or with a string
myReadableStreamBuffer.put("A String", "utf8");

The frequency cannot be 0 so this will introduce a certain delay. [1]: https://github.com/samcday/node-stream-buffer

Solution 5 - Javascript

You don't need to add a whole npm lib for a single file. i refactored it to typescript:

import { Readable, ReadableOptions } from "stream";

export class MultiStream extends Readable {
  _object: any;
  constructor(object: any, options: ReadableOptions) {
    super(object instanceof Buffer || typeof object === "string" ? options : { objectMode: true });
    this._object = object;
  }
  _read = () => {
    this.push(this._object);
    this._object = null;
  };
}

based on node-streamifier (the best option as said above).

Solution 6 - Javascript

You can use the standard NodeJS stream API for this - stream.Readable.from

const { Readable } = require('stream');
const stream = Readable.from(buffer);

> Note: Don't convert a buffer to string (buffer.toString()) if the buffer contains binary data. It will lead to corrupted binary files.

Solution 7 - Javascript

Here is a simple solution using streamifier module.

const streamifier = require('streamifier');
streamifier.createReadStream(new Buffer ([97, 98, 99])).pipe(process.stdout);

You can use Strings, Buffer and Object as its arguments.

Solution 8 - Javascript

This is my simple code for this.

import { Readable } from 'stream';

const newStream = new Readable({
                    read() {
                      this.push(someBuffer);
                    },
                  })

Solution 9 - Javascript

Try this:

const Duplex = require('stream').Duplex;  // core NodeJS API
function bufferToStream(buffer) {  
  let stream = new Duplex();
  stream.push(buffer);
  stream.push(null);
  return stream;
}

Source: Brian Mancini -> http://derpturkey.com/buffer-to-stream-in-node/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMasiarView Question on Stackoverflow
Solution 1 - JavascriptiamarkadytView Answer on Stackoverflow
Solution 2 - JavascriptMr5o1View Answer on Stackoverflow
Solution 3 - JavascriptBryan LarsenView Answer on Stackoverflow
Solution 4 - JavascriptvanthomeView Answer on Stackoverflow
Solution 5 - JavascriptJoel HarkesView Answer on Stackoverflow
Solution 6 - JavascriptIhor SakailiukView Answer on Stackoverflow
Solution 7 - JavascriptShwetabh ShekharView Answer on Stackoverflow
Solution 8 - JavascriptRichard VergisView Answer on Stackoverflow
Solution 9 - JavascriptmraxusView Answer on Stackoverflow