function
write
Use the fastest syscalls available to copy from input into destination.
If destination exists, it must be a regular file or symlink to a file. If destination's directory does not exist, it is created by default.
The file or file path to write to
The data to copy into destination
Options for the write
A promise that resolves with the number of bytes written.
Persist a Response body to disk.
The file to write to. If the file doesn't exist, it is created; if it does, it is overwritten. If input is smaller than destination, destination is truncated.
The Response whose body is written
Options for the write
A promise that resolves with the number of bytes written.
Persist a Response body to disk.
The file path to write to. If the file doesn't exist, it is created; if it does, it is overwritten. If input is smaller than the existing file, the file is truncated.
The Response whose body is written
A promise that resolves with the number of bytes written.
Use the fastest syscalls available to copy from input into destination.
If destination exists, it must be a regular file or symlink to a file.
On Linux, this uses copy_file_range.
On macOS, when the destination doesn't already exist, this uses clonefile() and falls back to fcopyfile().
The file to write to. If the file doesn't exist, it is created; if it does, it is overwritten. If input is smaller than destination, destination is truncated.
The file to copy from
A promise that resolves with the number of bytes written.
Use the fastest syscalls available to copy from input into destination.
If destination exists, it must be a regular file or symlink to a file.
On Linux, this uses copy_file_range.
On macOS, when the destination doesn't already exist, this uses clonefile() and falls back to fcopyfile().
The file path to write to. If the file doesn't exist, it is created; if it does, it is overwritten. If input is smaller than the existing file, the file is truncated.
The file to copy from
A promise that resolves with the number of bytes written.
Referenced types
interface BunFile
Blob powered by the fastest system calls available for operating on files.
This Blob is lazy: it does no work until you read from it.
sizeis not valid until the contents of the file are read at least once.typeis auto-set based on the file extension when possible
const file = Bun.file("./hello.json");
console.log(file.type); // "application/json"
console.log(await file.text()); // '{"hello":"world"}'Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes). Equivalent to
new Uint8Array(await blob.arrayBuffer())Deletes the file (same as unlink)
Does the file exist?
This returns true for regular files and FIFOs. It returns false for directories. A race condition can occur where the file is deleted or renamed after this is called but before you open it.
This does a system call to check if the file exists, which can be slow.
If using this in an HTTP server, it's faster to instead use
return new Response(Bun.file(path))and then anerrorhandler to handle exceptions.Instead of checking for a file's existence and then performing the operation, it is faster to just perform the operation and handle the error.
For empty Blob, this always returns true.
Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a
multipart/form-databody or anapplication/x-www-form-urlencodedbody.The blob's
typeproperty determines the format of the body.This is a non-standard addition to the
BlobAPI, to make it conform more closely to theBodyMixinAPI.Wrap this blob in a Bun.Image pipeline. Equivalent to
new Bun.Image(this, options)— the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works onBun.file(),Bun.s3(), fd-backed and in-memory blobs alike:await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
- begin?: number,end?: number,contentType?: string
Offset any operation on the file starting at
beginand ending atend.endis relative to 0Similar to
TypedArray.subarray. Does not copy the file, open the file, or modify the file.If
begin> 0, () is slower on macOS@param beginstart offset in bytes
@param endabsolute offset in bytes (relative to 0)
@param contentTypeMIME type for the new BunFile
begin?: number,contentType?: stringOffset any operation on the file starting at
beginSimilar to
TypedArray.subarray. Does not copy the file, open the file, or modify the file.If
begin> 0, Bun.write() is slower on macOS@param beginstart offset in bytes
@param contentTypeMIME type for the new BunFile
Returns a readable stream of the blob's contents
Returns a promise that resolves to the contents of the blob as a string
Deletes the file.
- data: string | ArrayBuffer | SharedArrayBuffer | BunFile | Request | Response | ArrayBufferView<ArrayBufferLike>,options?: { highWaterMark: number }): Promise<number>;
Write data to the file. This is equivalent to using Bun.write with a BunFile.
@param dataThe data to write.
@param optionsThe options to use for the write.
interface S3File
Represents a file in an S3-compatible storage service. Extends the Blob interface for compatibility with web APIs.
- readonly bucket?: string
The bucket name containing the file.
const file = s3.file("s3://my-bucket/file.txt"); console.log(file.bucket); // "my-bucket" - readonly name?: string
The name or path of the file in the bucket.
const file = s3.file("folder/image.jpg"); console.log(file.name); // "folder/image.jpg" - readonly readable: ReadableStream<Uint8Array<ArrayBuffer>>
Gets a readable stream of the file's content. Useful for processing large files without loading them entirely into memory.
// Basic streaming read const stream = file.stream(); for await (const chunk of stream) { console.log('Received chunk:', chunk); } - unlink: () => Promise<void>
Alias for
delete(), matching the Node.jsfsAPI naming.await file.unlink(); Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes). Equivalent to
new Uint8Array(await blob.arrayBuffer())Deletes the file from S3.
@returnsPromise that resolves when deletion is complete
// Basic deletion await file.delete();Checks if the file exists in S3, using an HTTP HEAD request that does not download the file.
@returnsPromise resolving to true if file exists, false otherwise
// Basic existence check if (await file.exists()) { console.log("File exists in S3"); }Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a
multipart/form-databody or anapplication/x-www-form-urlencodedbody.The blob's
typeproperty determines the format of the body.This is a non-standard addition to the
BlobAPI, to make it conform more closely to theBodyMixinAPI.Wrap this blob in a Bun.Image pipeline. Equivalent to
new Bun.Image(this, options)— the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works onBun.file(),Bun.s3(), fd-backed and in-memory blobs alike:await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
- ): string;
Generates a presigned URL for the file. The URL grants temporary access to the file without exposing credentials.
@param optionsConfiguration for the presigned URL
@returnsPresigned URL string
// Basic download URL const url = file.presign({ expiresIn: 3600 // 1 hour }); - begin?: number,end?: number,contentType?: string
Creates a new S3File representing a slice of the original file. Uses HTTP Range headers for efficient partial downloads.
@param beginStarting byte offset
@param endEnding byte offset (exclusive)
@param contentTypeOptional MIME type for the slice
@returnsA new S3File representing the specified range
// Reading file header const header = file.slice(0, 1024); const headerText = await header.text(); Returns a promise that resolves to the contents of the blob as a string
- data: string | ArrayBuffer | SharedArrayBuffer | Blob | BunFile | Request | Response | ArrayBufferView<ArrayBufferLike> | S3File | Archive,): Promise<number>;
Uploads data to S3. Supports various input types and automatically handles large files.
@param dataThe data to upload
@param optionsUpload configuration options
@returnsPromise resolving to number of bytes written
// Writing string data await file.write("Hello World", { type: "text/plain" }); Creates a writable stream for uploading data. Suitable for large files as it uses multipart upload.
@param optionsConfiguration for the upload
@returnsA NetworkSink for writing data
// Basic streaming write const writer = file.writer({ type: "application/json" }); writer.write('{"hello": '); writer.write('"world"}'); await writer.end();
class Blob
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes). Equivalent to
new Uint8Array(await blob.arrayBuffer())Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a
multipart/form-databody or anapplication/x-www-form-urlencodedbody.The blob's
typeproperty determines the format of the body.This is a non-standard addition to the
BlobAPI, to make it conform more closely to theBodyMixinAPI.Wrap this blob in a Bun.Image pipeline. Equivalent to
new Bun.Image(this, options)— the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works onBun.file(),Bun.s3(), fd-backed and in-memory blobs alike:await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
Returns a readable stream of the blob's contents
Returns a promise that resolves to the contents of the blob as a string
class Archive
Create and extract tar archives, with optional gzip compression.
Bun.Archive builds an archive from in-memory data, or wraps an existing archive so you can extract it to disk or memory.
Create an archive from an object:
const archive = new Bun.Archive({
"hello.txt": "Hello, World!",
"data.json": JSON.stringify({ foo: "bar" }),
"binary.bin": new Uint8Array([1, 2, 3, 4]),
});Get the archive contents as a
Uint8Array.Uses the compression settings specified when the Archive was created.
@returnsA promise that resolves with the archive data as a Uint8Array
Get tarball bytes:
const archive = new Bun.Archive(data); const bytes = await archive.bytes();- path: string,): Promise<number>;
Extract the archive contents to a directory on disk.
Creates the target directory and any necessary parent directories if they don't exist. Existing files are overwritten.
@param pathThe directory path to extract to
@param optionsOptional extraction options
@returnsA promise that resolves with the number of entries extracted (files, directories, and symlinks)
Extract all entries:
const archive = new Bun.Archive(tarballBytes); const count = await archive.extract("./extracted"); console.log(`Extracted ${count} entries`); - glob?: string | readonly string[]
Get the archive contents as a
MapofFileobjects.Each file in the archive is returned as a
Fileobject with:name: The file path within the archivelastModified: The file's modification time from the archive- Standard Blob methods (
text(),arrayBuffer(),stream(), etc.)
Only regular files are included; directories are not returned. File contents are loaded into memory, so for large archives consider using
extract()instead.@param globOptional glob pattern(s) to filter files. Supports the same syntax as Bun.Glob, including negation patterns (prefixed with
!). Patterns are matched against paths normalized to use forward slashes (/).@returnsA promise that resolves with a Map where keys are file paths (always using forward slashes
/as separators) and values are File objectsGet all files:
const entries = await archive.files(); for (const [path, file] of entries) { console.log(`${path}: ${file.size} bytes`); } - path: string,): Promise<void>;
Create an archive and write it to disk in one operation.
The data streams directly to disk, which is more efficient than creating an archive and then writing it separately.
@param pathThe file path to write the archive to
@param dataThe input data for the archive (same as
new Archive())@param optionsOptional archive options including compression settings
@returnsA promise that resolves when the write is complete
Write uncompressed tarball:
await Bun.Archive.write("output.tar", { "file1.txt": "content1", "file2.txt": "content2", });
class Response
This Fetch API interface represents the response to a request.
Returns a ReadableStream of the body decoded as UTF-8 text.
Multi-byte characters split across chunk boundaries are joined correctly. Throws a TypeError if the body has already been consumed or is locked.