使用Node JS将Uint8Array转换为流



将原生JavaScript Uint8Array转换为可读或转换Stream的最佳方法是什么?

我想出了如何把Uint8Array的缓冲区,不确定这是否有帮助:

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

标准的方法是用_read方法定义一个可读流:

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);

但是,您也可以使用事件流的readArray方法:

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

我使用Duplex而不是Readable (credit 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);

相关内容

  • 没有找到相关文章