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

# 增量写入文件

Bun 提供了增量写入文件的 API。适用于大文件，或长时间持续写入文件的情况。

在 `BunFile` 上调用 `.writer()` 以获取 `FileSink` 实例。它会缓冲数据；调用 `.flush()` 将缓冲区写入磁盘。你可以多次写入和刷新。

```ts theme={null}
const file = Bun.file("/path/to/file.txt");
const writer = file.writer();

writer.write("lorem");
writer.write("ipsum");
writer.write("dolor");

writer.flush();

// 继续写入和刷新
```

***

`.write()` 方法接受字符串或二进制数据。

```ts theme={null}
w.write("hello");
w.write(Buffer.from("there"));
w.write(new Uint8Array([0, 255, 128]));
writer.flush();
```

***

`FileSink` 还会在其内部缓冲区满时自动刷新。你可以使用 `highWaterMark` 选项配置缓冲区大小。

```ts theme={null}
const file = Bun.file("/path/to/file.txt");
const writer = file.writer({ highWaterMark: 1024 * 1024 }); // 1MB
```

***

写入完成后，调用 `.end()` 刷新缓冲区并关闭文件。

```ts theme={null}
writer.end();
```

***

完整文档：[FileSink](/runtime/file-io#incremental-writing-with-filesink)。
