获取可读流的部分范围

我想在给定ReadableStream的情况下返回一个特定的字节范围。这听起来很容易,但我找不到任何方法来跳过或从流中读取特定数量的字节,因为我们只能读取块。我宁愿不存储任何数据,而只是发送流。听起来我可以使用TransformStream和PipeThrough()来做到这一点。但是我需要一些帮助来包裹我的头脑。

示例:给定一个 1000 字节的 ReadableStream,我想返回另一个从字节 300 开始到字节 900 结束的流。

我知道这可以很容易地用节点创建ReadableStream()来完成,但我需要在浏览器中运行它,这样它就不能使用node。


森栏
浏览 69回答 1
1回答

慕桂英3389331

下面是一些框架代码,可帮助您入门:function byteRangeTransform(start, end) {&nbsp; let bytesSeen = 0;&nbsp; return new TransformStream({&nbsp; &nbsp; transform(chunk, controller) {&nbsp; &nbsp; &nbsp; const chunkStart = bytesSeen;&nbsp; &nbsp; &nbsp; const chunkEnd = bytesSeen + chunk.byteLength;&nbsp; &nbsp; &nbsp; bytesSeen += chunk.byteLength;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; // Six cases:&nbsp; &nbsp; &nbsp; // 1. Chunk entirely before start&nbsp; &nbsp; &nbsp; if (chunkEnd < start) {&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; // 2. Chunk starts before start, ends between start and end&nbsp; &nbsp; &nbsp; if (chunkStart < start && chunkEnd >= start && chunkEnd <= end) {&nbsp; &nbsp; &nbsp; &nbsp; const slice = /* TODO */;&nbsp; &nbsp; &nbsp; &nbsp; controller.enqueue(slice);&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; // 3. Chunk starts before start, ends after end&nbsp; &nbsp; &nbsp; if (chunkStart < start && chunkEnd > end) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; // 4. Chunk starts after start, ends between start and end&nbsp; &nbsp; &nbsp; // 5. Chunk starts after start, ends after end&nbsp; &nbsp; &nbsp; // 6. Chunk starts after end&nbsp; &nbsp; }&nbsp; });}const onlyInRange = originalReadable.pipeThrough(byteRangeTransform(300, 900));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript