> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 将 Buffer 转换为 ReadableStream

从 [`Buffer`](https://nodejs.org/api/buffer.html) 创建 [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) 的最简单方法是使用 `ReadableStream` 构造函数，并将整个数组作为一个数据块入队。对于较大的缓冲区，这种方法可能不理想，因为它没有将数据以较小的数据块进行“流式”处理。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const buf = Buffer.from("hello world");
const stream = new ReadableStream({
  start(controller) {
    controller.enqueue(buf);
    controller.close();
  },
});
```

***

为了以较小的数据块流式传输数据，首先从 `Buffer` 创建一个 `Blob` 实例。然后使用 [`Blob.stream()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/stream) 方法创建一个按指定大小分块流数据的 `ReadableStream`。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const buf = Buffer.from("hello world");
const blob = new Blob([buf]);
const stream = blob.stream();
```

***

可以通过向 `.stream()` 方法传入数字来设置块大小。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const buf = Buffer.from("hello world");
const blob = new Blob([buf]);

// 设置块大小为 1024 字节
const stream = blob.stream(1024);
```

***

完整的关于使用 Bun 操作二进制数据的文档见 [Docs > API > Binary Data](/runtime/binary-data#conversion)。
