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

runtime/file

84 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Example: read file to ArrayBuffer and access bytes

const path = "/path/to/package.json"; const file = Bun.file(path); const buffer = await file.arrayBuffer(); const bytes = new Int8Array(buffer); bytes[0]; bytes.length;

Read file as ArrayBuffer with .arrayBuffer()

To read a file as an ArrayBuffer, call the .arrayBuffer() method on a BunFile instance. This is an async operation that returns a promise resolving to an ArrayBuffer containing the file's binary content.

Check if file exists example

const path = "/path/to/package.json"; const file = Bun.file(path); await file.exists(); // boolean;

Bun.file() returns BunFile instance

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

BunFile.exists() method checks file existence

BunFile instances have an .exists() method that is awaited and returns a boolean indicating whether the file exists at the given path.

Reading and parsing JSON file with Bun

To read and parse a JSON file with Bun, call Bun.file(path) to get a BunFile instance, then call the asynchronous .json() method. The result is a plain JavaScript object.

BunFile.json() method signature

BunFile provides a .json() method that is asynchronous (returns a Promise). It reads and parses the contents of a JSON file, returning the parsed contents as a plain JavaScript object.

BunFile.type property for MIME type

The BunFile instance has a .type property that contains the MIME type. For JSON files, Bun automatically sets this to 'application/json;charset=utf-8'.

Read MIME type from file using Bun.file

Example: const file = Bun.file("./package.json"); file.type; returns "application/json;charset=utf-8". The BunFile class extends Blob, making the .type property available to read the MIME type.

BunFile .type property returns MIME type with charset

The .type property on a BunFile instance returns the MIME type. For example: application/json;charset=utf-8 for JSON files, text/html;charset=utf-8 for HTML files, and image/png for PNG files.

Bun.file() returns BunFile with MIME type property

The Bun.file() function accepts a file path and returns a BunFile instance. BunFile extends Blob and has a .type property that returns the MIME type of the file. The .type property includes charset information for text-based files.

Reading file as stream example

const path = "/path/to/package.json"; const file = Bun.file(path); const stream = file.stream(); for await (const chunk of stream) { chunk; // => Uint8Array } This example shows how to read a file at a given path as a ReadableStream and iterate over its chunks.

BunFile.stream() method signature and return type

The .stream() method on a BunFile instance returns a ReadableStream for consuming the file incrementally.

Reading file stream with for await

A ReadableStream from BunFile.stream() is an async iterable. You can read its chunks using for await...of, where each chunk is a Uint8Array.

Bun.file() example: relative path

const path = "./file.txt"; const file = Bun.file(path);

Read file as string with .text()

To read the contents of a BunFile as a string, call the .text() method on the BunFile instance. This is an asynchronous operation that returns a promise resolving to a string.

Bun.file() example: read file as string

const path = "/path/to/file.txt"; const file = Bun.file(path); const text = await file.text();

Bun resolves relative paths from current working directory

When using relative paths with Bun.file(), Bun resolves them from the current working directory, not from the script location.

Read file to Uint8Array example

Example of reading a file to Uint8Array: ```ts 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 ```

Read file to Uint8Array with .bytes()

To read a file into a Uint8Array, call the .bytes() method on a BunFile instance. This method is asynchronous and should be awaited. The resulting Uint8Array can be indexed by position (byteArray[0] for the first byte) and has a .length property.

Bun.file() returns BunFile instance

The Bun.file() function accepts a file path as a string and returns a BunFile instance. BunFile extends Blob, allowing you to read the file lazily in various formats.

fs/promises watch with for await example

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}`); }

fs.watch function signature and default behavior

The fs.watch function is implemented in Bun's node:fs module. By default, watch is shallow: changes to files in subdirectories are not detected. The callback receives event and filename parameters.

fs.watch callback signature

The fs.watch callback receives two parameters: event (the type of file system event) and filename (the name of the file that changed).

fs.watch recursive option

Pass the option { recursive: true } to fs.watch to listen for changes in subdirectories. When recursive is enabled, the callback receives a relativePath parameter instead of just filename.

fs/promises watch with async iteration

The fs/promises module provides a watch function that can be used with for await...of loops instead of callbacks. Each event object has eventType and filename properties.

watcher.close() method

Call watcher.close() to stop listening for file system changes. This is commonly done in response to a SIGINT signal (Ctrl-C).

fs.watch with callback example

import { watch } from "fs"; const watcher = watch(import.meta.dir, (event, filename) => { console.log(`Detected ${event} in ${filename}`); });

fs.watch with recursive option example

import { watch } from "fs"; const watcher = watch(import.meta.dir, { recursive: true }, (event, relativePath) => { console.log(`Detected ${event} in ${relativePath}`); });

fs.watch with SIGINT handler example

import { watch } from "fs"; const watcher = watch(import.meta.dir, (event, filename) => { console.log(`Detected ${event} in ${filename}`); }); process.on("SIGINT", () => { // close watcher when Ctrl-C is pressed console.log("Closing watcher..."); watcher.close(); process.exit(0); });

Delete directory with ENOENT handling

import { rm } from "node:fs/promises"; try { await rm("path/to/directory", { recursive: true }); } catch (error) { if (error.code === "ENOENT") { console.log("Directory doesn't exist"); } else { throw error; } }

rm from node:fs/promises API

The rm function from node:fs/promises can be used to recursively delete a directory and all its contents. It accepts a path string as the first argument and an options object as the second argument.

rm recursive option

The recursive option must be set to true to delete subdirectories and their contents when using rm from node:fs/promises.

rm force option

The force option, when set to true, prevents rm from throwing errors if the directory doesn't exist. When force is false or omitted, rm throws an error with code ENOENT if the directory doesn't exist.

Delete directory example with error handling

import { rm } from "node:fs/promises"; // Delete a directory and all its contents await rm("path/to/directory", { recursive: true, force: true });

Example: Delete a file and check if it exists

const file = Bun.file("path/to/file.txt"); await file.delete(); const exists = await file.exists(); // => false

HTML import hot module reloading

When using import HTML files with type: "text" in Bun with hot module reloading or watch mode, Bun automatically reloads whenever the .html file changes.

Import HTML file as text with type attribute

To import a .html file in Bun as a text file, use the import statement with a type: "text" attribute in the import assertion. The syntax is: import html from "./file.html" with { type: "text" };

HTML import example code

This example shows importing an HTML file as text and logging it: import html from "./file.html" with { type: "text" }; console.log(html); // <!DOCTYPE html><html><head>...

JSON imports with Import Attributes syntax

Bun supports the Import Attributes proposal syntax for JSON imports, which uses the 'with' keyword: import data from "./package.json" with { type: "json" }; This syntax explicitly declares the import type.

JSON imports with default syntax

Bun natively supports importing .json files using standard ES module syntax. You can import a JSON file like any other source file and access its properties as a JavaScript object.

JSON import example with default import

To import a JSON file in Bun, use: import data from "./package.json"; The imported data can be accessed as a JavaScript object with properties like data.name, data.version, and nested properties like data.author.name.

JSON imports with Import Attributes example

Example of importing JSON with explicit type declaration: import data from "./package.json" with { type: "json" }; data.name accesses the name property of the imported JSON object.

Importing TOML files

Bun natively supports importing .toml files as modules. You can import a TOML file using a standard import statement, and the parsed contents are available as an object with properties matching the TOML structure.

TOML import example

Example showing TOML import: given a data.toml file with structure `name = "bun"`, `version = "1.0.0"`, and `[author]` section with name and email fields, you can import it in TypeScript as `import data from "./data.toml";` and access properties like `data.name`, `data.version`, and `data.author.name`.

XML import default export structure

When importing an XML file with a default import like `import doc from "./config.xml"`, the imported module has the root element as a property. For example, if the root element is `<config>`, it is accessed as `doc.config`. Attributes are accessible via "@attributeName" keys (e.g., `doc.config["@env"]`), repeated elements become arrays, and all values are strings.

XML import named export for root element

The root element of an imported XML file is also available as a named import matching the root element's name. For example, from an XML file with root element `<config>`, you can import it as `import { config } from "./config.xml"`.

Bun.XML.parse() for runtime XML parsing

Bun.XML.parse() parses XML strings at runtime. It takes an XML string as input and returns a parsed object with the same structure as imported XML files: root element as a property, attributes accessible via "@attributeName" keys, repeated elements as arrays, and all values as strings.

Bun.XML.parse() example

const data = Bun.XML.parse(` <user id="7"> <name>John Doe</name> <hobby>reading</hobby> <hobby>coding</hobby> </user> `); console.log(data.user.name); // => "John Doe" console.log(data.user.hobby); // => ["reading", "coding"] console.log(data.user["@id"]); // => "7"

XML import with default export example

import doc from "./config.xml"; doc.config["@env"]; // => "production" doc.config.database["@host"]; // => "localhost" doc.config.server["@port"]; // => "3000" doc.config.feature.map(f => f["@name"]); // => ["auth", "rateLimit"]

XML import with named export example

import { config } from "./config.xml"; console.log(config.database["@name"]); // => "myapp" console.log(Number(config.server["@timeout"])); // => 30

Import XML files natively

Bun natively supports .xml imports. The module is the parsed document: one key for the root element, "@name" keys for attributes, arrays for repeated elements, and every value a string.

Bun.write() with relative path example

const path = "./file.txt"; await Bun.write(path, "Lorem ipsum");

Bun.write() to write string to file

Bun.write() writes a string to disk at an absolute or relative path. The first argument is the destination (a path string or BunFile object), and the second argument is the data to write. It returns the number of bytes written to disk as a number.

Bun.write() resolves relative paths from current working directory

When passing a relative path to Bun.write(), it resolves relative to the current working directory.

Bun.write() with BunFile destination example

const path = Bun.file("./file.txt"); await Bun.write(path, "Lorem ipsum");

Bun.write() returns bytes written

const path = "./file.txt"; const bytes = await Bun.write(path, "Lorem ipsum"); // => 11

fs.appendFile with encoding example

import { appendFile } from "node:fs"; appendFile("message.txt", "data to append", "utf8", callback);

fs.appendFileSync with encoding example

import { appendFileSync } from "node:fs"; appendFileSync("message.txt", "data to append", "utf8");

fs.appendFile asynchronous file append

The fs.appendFile function asynchronously appends data to a file, creating the file if it does not yet exist. The content can be a string or a Buffer. It can be imported from node:fs/promises for Promise-based usage: await appendFile('message.txt', 'data to append'). It can also be imported from node:fs for callback-based usage: appendFile('message.txt', 'data to append', err => { ... }). An optional encoding parameter can be specified, such as 'utf8': appendFile('message.txt', 'data to append', 'utf8', callback).

Give your agent this brain