50 lines
1.0 KiB
Plaintext
50 lines
1.0 KiB
Plaintext
---
|
|
title: Write a file incrementally
|
|
sidebarTitle: Incremental write
|
|
mode: center
|
|
---
|
|
|
|
Bun provides an API for incrementally writing to a file. Use it for large files, or when writing to a file over a long period of time.
|
|
|
|
Call `.writer()` on a `BunFile` to retrieve a `FileSink` instance. The `FileSink` buffers data. Call `.flush()` to write the buffer to disk. You can write & flush many times.
|
|
|
|
```ts
|
|
const file = Bun.file("/path/to/file.txt");
|
|
const writer = file.writer();
|
|
|
|
writer.write("lorem");
|
|
writer.write("ipsum");
|
|
writer.write("dolor");
|
|
|
|
writer.flush();
|
|
|
|
// continue writing & flushing
|
|
```
|
|
|
|
---
|
|
|
|
The `.write()` method accepts strings or binary data.
|
|
|
|
```ts
|
|
writer.write("hello");
|
|
writer.write(Buffer.from("there"));
|
|
writer.write(new Uint8Array([0, 255, 128]));
|
|
writer.flush();
|
|
```
|
|
|
|
---
|
|
|
|
The `FileSink` also auto-flushes when its internal buffer is full.
|
|
|
|
---
|
|
|
|
When you're done writing, call `.end()` to flush the buffer and close the file.
|
|
|
|
```ts
|
|
writer.end();
|
|
```
|
|
|
|
---
|
|
|
|
Full documentation: [FileSink](/runtime/file-io#incremental-writing-with-filesink).
|