Keep State Between Runs#
A run starts with no memory of the last one, but the file system does. This example keeps a small JSON file between runs and increments a counter, the building block for checkpoints, deduplication, and “only act when something changed” jobs.
The Script#
// state.js
import fs from "fs";
const file = "/state.json";
let state = { runs: 0, lastRunAt: null };
try {
state = JSON.parse(await fs.readTextFile(file));
} catch {
// First run: no state file yet, keep the defaults above.
}
state.runs += 1;
state.lastRunAt = new Date().toISOString();
await fs.writeTextFile(file, JSON.stringify(state, null, 2));
console.log(`This job has run ${state.runs} time(s)`);
How It Works#
- The first time the job runs there is no
/state.json, sofs.readTextFilethrows and thecatchleaves the defaults in place. - After that, the file is read, updated, and written back, so each run builds on the last.
- Keep the file small. It counts against your storage quota, and it is loaded into memory each time it is read.
Setup#
Create a job that points at state.js and run it a few times: the
counter climbs by one each run.