1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
|
{% callout %}
**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. Existing Node.js projects may use Bun's [nearly complete](/docs/ecosystem/nodejs#node_fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module.
{% /callout %}
Bun provides a set of optimized APIs for reading and writing files.
## Reading files
`Bun.file(path): BunFile`
Create a `BunFile` instance with the `Bun.file(path)` function. A `BunFile` represents represents a lazily-loaded file; initializing it does not actually read the file from disk.
```ts
const foo = Bun.file("foo.txt"); // relative to cwd
foo.size; // number of bytes
foo.type; // MIME type
```
The reference conforms to the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) interface, so the contents can be read in various formats.
```ts
const foo = Bun.file("foo.txt");
await foo.text(); // contents as a string
await foo.stream(); // contents as ReadableStream
await foo.arrayBuffer(); // contents as ArrayBuffer
```
File references can also be created using numerical [file descriptors](https://en.wikipedia.org/wiki/File_descriptor) or `file://` URLs.
```ts
Bun.file(1234);
Bun.file(new URL(import.meta.url)); // reference to the current file
```
A `BunFile` can point to a location on disk where a file does not exist.
```ts
const notreal = Bun.file("notreal.txt");
notreal.size; // 0
notreal.type; // "text/plain;charset=utf-8"
```
The default MIME type is `text/plain;charset=utf-8`, but it can be overridden by passing a second argument to `Bun.file`.
```ts
const notreal = Bun.file("notreal.json", { type: "application/json" });
notreal.type; // => "text/plain;charset=utf-8"
```
For convenience, Bun exposes `stdin`, `stdout` and `stderr` as instances of `BunFile`.
```ts
Bun.stdin; // readonly
Bun.stdout;
Bun.stderr;
```
## Writing files
`Bun.write(destination, data): Promise<number>`
The `Bun.write` function is a multi-tool for writing payloads of all kinds to disk.
The first argument is the `destination` which can have any of the following types:
- `string`: A path to a location on the file system. Use the `"path"` module to manipulate paths.
- `URL`: A `file://` descriptor.
- `BunFile`: A file reference.
The second argument is the data to be written. It can be any of the following:
- `string`
- `Blob` (including `BunFile`)
- `ArrayBuffer` or `SharedArrayBuffer`
- `TypedArray` (`Uint8Array`, et. al.)
- `Response`
All possible permutations are handled using the fastest available system calls on the current platform.
{% details summary="See syscalls" %}
{% table %}
- Output
- Input
- System call
- Platform
---
- file
- file
- copy_file_range
- Linux
---
- file
- pipe
- sendfile
- Linux
---
- pipe
- pipe
- splice
- Linux
---
- terminal
- file
- sendfile
- Linux
---
- terminal
- terminal
- sendfile
- Linux
---
- socket
- file or pipe
- sendfile (if http, not https)
- Linux
---
- file (doesn't exist)
- file (path)
- clonefile
- macOS
---
- file (exists)
- file
- fcopyfile
- macOS
---
- file
- Blob or string
- write
- macOS
---
- file
- Blob or string
- write
- Linux
{% /table %}
{% /details %}
To write a string to disk:
```ts
const data = `It was the best of times, it was the worst of times.`;
await Bun.write("output.txt", data);
```
To copy a file to another location on disk:
```js
const input = Bun.file("input.txt");
const output = Bun.file("output.txt"); // doesn't exist yet!
await Bun.write(output, input);
```
To write a byte array to disk:
```ts
const encoder = new TextEncoder();
const data = encoder.encode("datadatadata"); // Uint8Array
await Bun.write("output.txt", data);
```
To write a file to `stdout`:
```ts
const input = Bun.file("input.txt");
await Bun.write(Bun.stdout, input);
```
To write an HTTP response to disk:
```ts
const response = await fetch("https://bun.sh");
await Bun.write("index.html", response);
```
## Benchmarks
The following is a 3-line implementation of the Linux `cat` command.
```ts#cat.ts
// Usage
// $ bun ./cat.ts ./path-to-file
import { resolve } from "path";
const path = resolve(process.argv.at(-1));
await Bun.write(Bun.stdout, Bun.file(path));
```
To run the file:
```bash
$ bun ./cat.ts ./path-to-file
```
It runs 2x faster than GNU `cat` for large files on Linux.
{% image src="/images/cat.jpg" /%}
## Reference
```ts
interface Bun {
stdin: BunFile;
stdout: BunFile;
stderr: BunFile;
file(path: string | number | URL, options?: { type?: string }): BunFile;
write(
destination: string | number | FileBlob | URL,
input: string | Blob | ArrayBuffer | SharedArrayBuffer | TypedArray | Response,
): Promise<number>;
}
interface BunFile {
readonly size: number;
readonly type: string;
text(): Promise<string>;
stream(): Promise<ReadableStream>;
arrayBuffer(): Promise<ArrayBuffer>;
json(): Promise<any>;
}
```
|