当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js ReadableStreamBYOBReader用法及代码示例

类:ReadableStreamBYOBReader

历史
版本变化
v18.0.0

这个类现在暴露在全局对象上。

v16.5.0

添加于:v16.5.0

ReadableStreamBYOBReader 是面向字节的 <ReadableStream> 的替代消费者(在创建 ReadableStream 时将 underlyingSource.type 设置为等于 'bytes' 的消费者)。

BYOB 是“自带缓冲区”的缩写。这是一种模式,可以更有效地读取面向字节的数据,从而避免多余的复制。

import {
  open
} from 'node:fs/promises';

import {
  ReadableStream
} from 'node:stream/web';

import { Buffer } from 'node:buffer';

class Source {
  type = 'bytes';
  autoAllocateChunkSize = 1024;

  async start(controller) {
    this.file = await open(new URL(import.meta.url));
    this.controller = controller;
  }

  async pull(controller) {
    const view = controller.byobRequest?.view;
    const {
      bytesRead,
    } = await this.file.read({
      buffer: view,
      offset: view.byteOffset,
      length: view.byteLength
    });

    if (bytesRead === 0) {
      await this.file.close();
      this.controller.close();
    }
    controller.byobRequest.respond(bytesRead);
  }
}

const stream = new ReadableStream(new Source());

async function read(stream) {
  const reader = stream.getReader({ mode: 'byob' });

  const chunks = [];
  let result;
  do {
    result = await reader.read(Buffer.alloc(100));
    if (result.value !== undefined)
      chunks.push(Buffer.from(result.value));
  } while (!result.done);

  return Buffer.concat(chunks);
}

const data = await read(stream);
console.log(Buffer.from(data).toString());

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 ReadableStreamBYOBReader。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。