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.mkdirwith{ recursive: true }creates the directory and does nothing if it already exists, so it is safe to call every run.fs.writeTextFileoverwrites the file with a UTF-8 string.fs.readTextFilereads 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.