Reputation: 28364
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);
Upvotes: 3
Views: 12669
Reputation: 2644
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);
Upvotes: 3
Reputation: 10104
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);
Upvotes: 3