Read and Write Files#

Every account has a persistent file system. This example creates a directory, writes a file into it, and reads the text back. The file survives between runs, so the next run can read what this one wrote.

The Script#

// notes.js
import fs from "fs";

const path = "/notes/today.txt";
const text = `Written at ${new Date().toISOString()}`;

await fs.mkdir("/notes", { recursive: true });
await fs.writeTextFile(path, text);

const saved = await fs.readTextFile(path);
console.log(`Saved: ${saved}`);

How It Works#

  • fs.mkdir with { recursive: true } creates the directory and does nothing if it already exists, so it is safe to call every run.
  • fs.writeTextFile overwrites the file with a UTF-8 string.
  • fs.readTextFile reads it back as a UTF-8 string.

For binary data, work in bytes instead: fs.readFile returns a Uint8Array, and fs.writeFile accepts a Uint8Array or a ReadableStream of bytes.

const bytes = await fs.readFile("/logo.png"); // Uint8Array
await fs.writeFile("/logo-copy.png", bytes);

Setup#

Paths are absolute and always start with /. Create a job that points at notes.js and run it twice to see the timestamp update.