Skip to main content
On this page

@std/streams

Overview Jump to heading

Utilities for working with the Streams API.

Includes buffering and conversion.

import { toText } from "@std/streams";
import { assertEquals } from "@std/assert";

const stream = ReadableStream.from(["Hello, world!"]);
const text = await toText(stream);

assertEquals(text, "Hello, world!");

Add to your project Jump to heading

deno add jsr:@std/streams

See all symbols in @std/streams on

什么是 Web Streams? Jump to heading

Web Streams 提供了一种在 JavaScript 中处理流式数据的标准方式。它们允许你在数据陆续到达时逐块处理,而不必等待整个数据集全部可用。这对于处理大文件、网络请求或任何随着时间产生数据的场景特别有用。

为什么使用 @std/streams? Jump to heading

用于高效地缓冲、转换和组合 Web Streams。

示例 Jump to heading

import { copy, readerFromStreamReader, writeAll } from "@std/streams";

// 通过流将一个文件复制到另一个文件
const r = await Deno.open("input.txt");
const w = await Deno.open("output.txt", {
  create: true,
  write: true,
  truncate: true,
});
await copy(r, w);
r.close();
w.close();

// 将 ReadableStreamDefaultReader 转换为 Deno.Reader
const res = await fetch("https://deno.land");
const denoReader = readerFromStreamReader(res.body!.getReader());
await writeAll(
  Deno.stdout,
  new Uint8Array(await new Response(denoReader).arrayBuffer()),
);

小贴士 Jump to heading

  • 对于大数据负载,优先使用流式处理,以减少内存压力。
  • 使用诸如 toTexttoArrayBufferiterateReader 等辅助函数进行转换。

你找到了你需要的东西吗?

编辑此页面
隐私政策