High-performance file system operations with the BunFile interface, atomic writes, memory mapping, and comprehensive I/O capabilities optimized for speed and safety.
Create BunFile instances from various sources including file paths, buffers, and file descriptors.
/**
* Create a BunFile from a file path or URL
* @param path - File path as string or URL
* @param options - Optional file options
* @returns BunFile instance
*/
function Bun.file(path: string | URL, options?: BunFileOptions): BunFile;
/**
* Create a BunFile from buffer data
* @param data - Buffer or typed array data
* @param options - Optional file options
* @returns BunFile instance
*/
function Bun.file(data: ArrayBufferLike | Uint8Array, options?: BunFileOptions): BunFile;
/**
* Create a BunFile from a file descriptor
* @param fd - File descriptor number
* @param options - Optional file options
* @returns BunFile instance
*/
function Bun.file(fd: number, options?: BunFileOptions): BunFile;
interface BunFileOptions {
type?: string;
lastModified?: number;
}Usage Examples:
import { file } from "bun";
// From file path
const configFile = Bun.file("./config.json");
// From buffer data
const buffer = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
const bufferFile = Bun.file(buffer, { type: "text/plain" });
// From file descriptor (advanced)
const fd = 3; // stdout
const stdoutFile = Bun.file(fd);Enhanced File interface with additional methods for efficient reading and metadata access.
interface BunFile extends File {
/** File size in bytes */
readonly size: number;
/** MIME type of the file */
readonly type: string;
/** Last modified timestamp */
readonly lastModified: number;
/** File name */
readonly name: string;
/**
* Check if file exists on disk
* @returns Promise resolving to true if file exists
*/
exists(): Promise<boolean>;
/**
* Read file as JSON and parse
* @returns Promise resolving to parsed JSON object
*/
json<T = any>(): Promise<T>;
/**
* Read file as UTF-8 text
* @returns Promise resolving to text content
*/
text(): Promise<string>;
/**
* Read file as ArrayBuffer
* @returns Promise resolving to ArrayBuffer
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Read file as Uint8Array bytes
* @returns Promise resolving to Uint8Array
*/
bytes(): Promise<Uint8Array>;
/**
* Get readable stream of file contents
* @returns ReadableStream for streaming file data
*/
stream(): ReadableStream<Uint8Array>;
/**
* Create a Blob slice of the file
* @param start - Start byte position
* @param end - End byte position
* @param contentType - MIME type for the slice
* @returns BunFile slice
*/
slice(start?: number, end?: number, contentType?: string): BunFile;
}Usage Examples:
const file = Bun.file("data.json");
// Check existence before reading
if (await file.exists()) {
const data = await file.json();
console.log("Loaded data:", data);
}
// Read as different formats
const textContent = await file.text();
const binaryData = await file.bytes();
const buffer = await file.arrayBuffer();
// Stream large files
const stream = file.stream();
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log("Chunk:", value);
}High-performance file writing with atomic operations and multiple input type support.
/**
* Write data to a file with high performance and atomic operations
* @param destination - File path, descriptor, or BunFile to write to
* @param input - Data to write (string, buffer, stream, etc.)
* @param options - Write options
* @returns Promise resolving to number of bytes written
*/
function Bun.write(
destination: string | number | FileDescriptor | BunFile,
input: string | ArrayBufferLike | BunFile | Response | Blob | ReadableStream,
options?: WriteOptions
): Promise<number>;
interface WriteOptions {
/** Create parent directories if they don't exist */
createPath?: boolean;
}
type FileDescriptor = number;Usage Examples:
// Write string to file
const bytesWritten = await Bun.write("output.txt", "Hello, World!");
// Write binary data
const buffer = new Uint8Array([72, 101, 108, 108, 111]);
await Bun.write("binary.dat", buffer);
// Copy file efficiently
const sourceFile = Bun.file("source.pdf");
await Bun.write("copy.pdf", sourceFile);
// Stream to file
const response = await fetch("https://example.com/data.json");
await Bun.write("downloaded.json", response);
// Create directories automatically
await Bun.write("deep/nested/path/file.txt", "content", {
createPath: true
});Memory-map files for efficient random access to large files.
/**
* Memory-map a file for efficient random access
* @param path - Path to file to map
* @param options - Memory mapping options
* @returns Uint8Array view of the mapped file
*/
function Bun.mmap(
path: string,
options?: MmapOptions
): Uint8Array;
interface MmapOptions {
/** Offset in bytes from start of file */
offset?: number;
/** Length in bytes to map */
length?: number;
}Usage Examples:
// Map entire file
const mappedFile = Bun.mmap("large-data.bin");
console.log("File size:", mappedFile.length);
// Access specific bytes directly
const firstByte = mappedFile[0];
const lastByte = mappedFile[mappedFile.length - 1];
// Map partial file
const partialMap = Bun.mmap("large-data.bin", {
offset: 1024, // Start at 1KB
length: 4096 // Map 4KB
});Access to standard input, output, and error streams as BunFile instances.
/** Standard input stream as BunFile */
declare const Bun.stdin: BunFile;
/** Standard output stream as BunFile */
declare const Bun.stdout: BunFile;
/** Standard error stream as BunFile */
declare const Bun.stderr: BunFile;Usage Examples:
// Read from stdin
const input = await Bun.stdin.text();
console.log("You typed:", input);
// Write to stdout/stderr
await Bun.write(Bun.stdout, "Hello from stdout\n");
await Bun.write(Bun.stderr, "Error message\n");Efficient memory allocation and buffer operations.
/**
* Allocate uninitialized buffer for performance-critical operations
* @param size - Buffer size in bytes
* @returns Uninitialized Uint8Array
*/
function Bun.allocUnsafe(size: number): Uint8Array;Usage Examples:
// Allocate buffer for binary operations
const buffer = Bun.allocUnsafe(1024);
// Fill with data (buffer contents are undefined initially)
buffer.fill(0);
// Use for high-performance operations
const data = new DataView(buffer.buffer);
data.setUint32(0, 0x12345678);/** Union type for path-like inputs */
type PathLike = string | URL | Buffer | Uint8Array;
/** Union type for buffer sources */
type BufferSource = ArrayBufferView | ArrayBuffer;
/** Union type for string or buffer data */
type StringOrBuffer = string | BufferSource;
/** File system error with additional context */
interface FileSystemError extends Error {
code: string;
path?: string;
errno?: number;
syscall?: string;
}