In Ignore Yesterday’s Late Reply, a run counter, latestRun, let the kitchen panel ignore Tuesday’s late report. Erik has a different question about the routine: how many mornings has it run? So each run adds one to a count in a log file, morning-log.json, which keeps the count after Node.js stops.
In this lesson, you’ll let Tuesday’s late run and Wednesday’s run update that log at overlapping times, each taking turns at its await. You’ll see where the two updates get in each other’s way, then line them up so each waits its turn. Start with the function that records a run.
Count the Runs in a File
Saving a number in a file takes three steps: read the file, change the number, and write the file back. In the real routine, readFile() and writeFile() from node:fs/promises would do the reading and writing. The promise from writeFile() fulfills once the file holds the new text, and rejects if writing fails.
Real file timing changes from run to run, so this lesson uses a stand-in for the file, as the course does for devices. Work in your morning folder and save it as log_store.mjs:
log_store.mjs
let saved = JSON.stringify({ runs: 0 });
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function readLog() {
await wait(100);
return saved;
}
export async function writeLog(text) {
await wait(100);
saved = text;
}
The variable saved stands in for the file’s contents. Because the stand-in is a toy, it starts again at zero runs each time Node.js starts, which a real file wouldn’t. Reading and writing each take a fixed 100 milliseconds, so two overlapping updates line up the same way on every run. Now save the function that records a run as run_log.mjs: