3

What's the best way to take a native JavaScript Uint8Array and turn it into a readable or transform Stream?

I figured out how to turn Uint8Array's into Buffers, not sure if this helps:

var uint8array = new Uint8Array();
var buffer = new Buffer(uint8array);

2 Answers 2

3

The standard way would be to define a readable stream with a _read method:

var Stream = require('stream');

var myStream = new Stream.Readable();
var i = 0;
var data = [1, 2, 3, 4];

myStream._read = function(size) {
  var pushed = true;
  while (pushed && i < data.length) {
    pushed = this.push(data[i++]);
  }

  if (i === data.length) {
    this.push(null);
  }
};

myStream.pipe(somewhere);

However, you can also use event-stream's readArray method:

var es = require('event-stream');
var data = [1, 2, 3, 4];
var myStream = es.readArray(data);

myStream.pipe(somewhere);
Sign up to request clarification or add additional context in comments.

1 Comment

Trying the "Standard Way" I get an error: "TypeError: Invalid non-string/buffer chunk". I'm piping it to process.stdout as a test. Am I doing something wrong, or is this broken?
3

What made it work for me was using Duplex instead of Readable (credit goes to Brian Mancini ):

import { Duplex } from 'stream';
// Or non ES6 syntax:
// const Duplex = require('stream').Duplex
let stream = new Duplex();
stream.push(buffer);
stream.push(null);
stream.pipe(process.stdout);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.