當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。