new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · all subjects

file i/o & paths

23 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Bun.file() returns a lazily-loaded BunFile instance

Bun.file() accepts a file path as a string and returns a lazily-loaded BunFile instance. This BunFile can be passed directly to the Response constructor to stream the file as an HTTP response.

Reading stdin chunks with Bun.stdin.stream()

You can read chunks from stdin using for await (const chunk of Bun.stdin.stream()). Each chunk is a Uint8Array. To convert a chunk to text, use Buffer.from(chunk).toString() which assumes UTF-8 encoding.

Read file to Uint8Array with .bytes()

To read a file into a Uint8Array, use the .bytes() method on a BunFile instance. This is an async operation that returns a promise resolving to a Uint8Array containing the file's binary data.

BunFile .bytes() example

const path = "/path/to/package.json"; const file = Bun.file(path); const byteArray = await file.bytes(); byteArray[0]; // first byte byteArray.length; // length of byteArray

SIGINT signal handler for graceful watcher shutdown

To stop listening for changes when the process receives a SIGINT signal (Ctrl-C), use process.on("SIGINT", ...) to call watcher.close() and process.exit(0).

fs.watch basic usage with callback

The fs.watch function from the "fs" module listens for file system changes. By default, the watch is shallow and does not detect changes in subdirectories. The callback receives an event type and filename parameter: watch(import.meta.dir, (event, filename) => { console.log(`Detected ${event} in ${filename}`); });

fs.watch recursive option for subdirectories

To listen for changes in subdirectories, pass the recursive: true option to fs.watch. When recursive mode is enabled, the callback receives the event type and a relative path: watch(import.meta.dir, { recursive: true }, (event, relativePath) => { console.log(`Detected ${event} in ${relativePath}`); });

fs/promises watch with for await...of

The fs/promises module provides a watch function that can be used with for await...of loops instead of callbacks. The event object has eventType and filename properties: import { watch } from "fs/promises"; const watcher = watch(import.meta.dir); for await (const event of watcher) { console.log(`Detected ${event.eventType} in ${event.filename}`); }

watcher.close() stops file watching

Call watcher.close() to stop listening for file system changes. This is commonly done when the process receives a SIGINT signal, such as when the user presses Ctrl-C.

Bun.file() returns a BunFile instance

The Bun.file() function accepts a file path as a string and returns a BunFile instance. BunFile extends the Blob class.

BunFile extends Blob

The BunFile class extends Blob, so a BunFile instance can be passed directly to Bun.write() as the data argument.

Write Blob to file with Bun.write()

To write a Blob to a file, pass the file path as a string and a Blob instance to Bun.write(). For example: const data = new Blob(['Lorem ipsum']); await Bun.write('/path/to/file.txt', data);

Copy file contents with Bun.write() and BunFile

To copy the contents of one file to another, use Bun.file() to read the source file and pass the resulting BunFile to Bun.write(). For example: const data = Bun.file('./in.txt'); await Bun.write('./out.txt', data);

Bun.write() with Response object

Use Bun.write() to write a Response to disk. Bun writes the body of the Response to the destination. The first argument is a destination, like an absolute path or BunFile instance. The second argument is the data to write, which can be a Response object.

Bun.write() example writing fetch response to file

const result = await fetch("https://bun.com"); const path = "./file.txt"; await Bun.write(path, result);

Write ReadableStream to file using writer()

To write a ReadableStream to disk, call .writer() on a BunFile to get a FileSink. The stream is an async iterable, so write each of its chunks to the FileSink with for await. Then call .end() to flush the buffer and close the file.

Example: write ReadableStream to file

const stream: ReadableStream = ...; const path = "./file.txt"; const writer = Bun.file(path).writer(); for await (const chunk of stream) { writer.write(chunk); } await writer.end();

BunFile.writer() creates file if missing but does not truncate

.writer() creates the file if it doesn't exist, but does not truncate an existing file. If the file may already exist, delete it first.

FileSink.write() with different data types example

writer.write("hello"); writer.write(Buffer.from("there")); writer.write(new Uint8Array([0, 255, 128])); writer.flush();

FileSink for incremental file writing

Bun provides a FileSink API for incrementally writing to files. Call .writer() on a BunFile to retrieve a FileSink instance. The FileSink buffers data and writes to disk when .flush() is called. You can write and flush multiple times.

FileSink auto-flush behavior

The FileSink automatically flushes when its internal buffer becomes full.

Creating a FileSink example

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

Import and serve static HTML files

HTML files can be imported as modules in Bun TypeScript files. For example, `import index from './index.html'` makes the HTML file available as a variable that can be used directly as a route handler: `routes: {"/": index}`.

Give your agent this brain