So far, every delayed callback in this course has waited for a timer. In the last exercise, you tallied the laundry log in chunks so Kofi’s reminders kept arriving. Timers aren’t the only thing a program waits for, though. Reading a file from disk takes time too, and the house rota at 14 Ferris Road lives in a small text file.
In this lesson, you’ll read that rota with a function that calls you back when the file has loaded. You’ll handle the error it reports when the file isn’t there, and you’ll run two reads in order when the second one depends on the first. Start by reading the rota from its file.
Read the Rota From a File
The housemates take turns on laundry duty, emptying the dryer’s lint filter and pairing the lost socks. The order lives in rota.txt, one name per line, with this week’s housemate first. Save it in your laundry folder:
rota.txt
Ines
Kofi
Wren
Dev
Node.js reads files with readFile() from its built-in fs module, short for file system. You import it as you’d import from one of your own modules. The node: prefix in "node:fs" tells Node.js that the module is built in rather than a file in your project. Here’s read_rota.mjs:
read_rota.mjs
import { readFile } from "node:fs";
readFile("rota.txt", "utf8", (err, text) => {
const name = text.trim().split("\n")[0].trim();
console.log(`On laundry duty this week: ${name}`);
});
console.log("Reading the rota...");
You pass readFile() three arguments: the file’s path, the encoding "utf8" so you get the contents as a string, and a callback. Run it from the laundry folder:
$ node read_rota.mjs
Reading the rota...
On laundry duty this week: Ines
The last line of the script printed first. That’s now and later again. readFile() hands the job and your callback to Node.js and returns at once, so the script carries on and ends.
Node.js keeps the callback in the waiting area while it reads the file. When the contents are ready, the callback joins the task queue, and the event loop moves it onto the empty call stack, as it would a timer callback.
Inside the callback, the first line turns the file’s contents into a name. The first .trim() drops the newline at the end of the file, .split("\n") breaks the rest into lines, and [0] takes the first one. The second .trim() is for Windows, where many editors end each line with \r\n, a carriage return before the newline. Splitting on "\n" leaves that \r behind, as this REPL session shows: