Capstone A: the task file
The model of the previous lesson is worth nothing until the list outlives the process. The tracker keeps its tasks in one JSON file beside the program, and the two functions of this lesson are the only code in the project that touches it: load turns the file into an array of tasks and save writes the array back.
The folder holds the manifest, the lint config and the model of the previous lesson, and the check program that runs them. This lesson adds src/storage.js and rewrites the check program, which is the only file of the project that a later lesson removes.
The write is the interesting half. A program that opens the file and writes the new text can die in the middle, and the reader then has a file that is half one list and half another. The lesson writes a temporary file beside the target and renames it, which replaces the old file in one step, and it checks the folder afterwards to show that nothing else is left in it.
The file format
The file holds one object with two fields: version, so a later change can tell an old file from a new one, and tasks, the array. The tasks are written by toJSON, so the file holds exactly the three fields of the model and no method and no prototype.
The file tasks.json, written by the check of this lesson:
{
"version": 1,
"tasks": [
{
"id": 1,
"title": "write the model",
"done": false
},
{
"id": 2,
"title": "read the JSON file",
"done": false
}
]
}
The indentation is two spaces and the file ends with a newline, which costs one byte and makes the file readable in a diff: a task that is added or marked as done changes a few lines rather than the whole file. The exact bytes are what the check of this lesson reads back, so the format is pinned by a program and not only by this page.
A file that is not there
The first run of the tracker finds no file, and that is not an error: it is an empty list. The loader asks for the file, catches the one error code that means "not there" and lets every other error through, which is the pattern that the lesson on reading files builds on one call.
Catching every error and returning an empty list would be worse than letting it out: a file whose permissions are wrong would read as a tracker with no tasks, and the next save would write an empty list over a file that is only unreadable.
The file src/storage.js:
vi src/storage.js
const { readFile, rename, writeFile } = require('node:fs/promises');
const { Task } = require('./task');
async function load(file) {
let text;
try {
text = await readFile(file, 'utf8');
} catch (error) {
if (error.code === 'ENOENT') {
return [];
}
throw error;
}
const data = JSON.parse(text);
if (!Array.isArray(data.tasks)) {
throw new Error('the file has no tasks array');
}
return data.tasks.map((entry) => Task.fromJSON(entry));
}
async function save(file, tasks) {
const data = { version: 1, tasks: tasks.map((task) => task.toJSON()) };
const temp = file + '.tmp';
await writeFile(temp, JSON.stringify(data, null, 2) + '\n');
await rename(temp, file);
return tasks.length;
}
module.exports = { load, save };
Task.fromJSON is the only way a task is built from the file, so the validation of the previous lesson applies to a file that a person edited as well as to a title that a person typed. The version field is read and thrown away for now; the exercise at the end asks for the check that would use it.
The write and the rename
The save builds the object, stringifies it and writes it to tasks.json.tmp, then renames that file over tasks.json. A rename inside one folder is a single operation of the file system: a reader sees the old file or the new one, never a half-written one, and a process that dies before the rename leaves the old file untouched.
The temporary file has to be in the same folder, because a rename across two file systems is a copy followed by a delete and loses the guarantee. It also has to be removed when the write fails, which is the part a real tool adds with a finally; the check of this lesson writes to a folder it owns, so it only asks whether the temporary file is gone after a successful save.
The check program works in a folder made with mkdtemp and removes it at the end, which is the pattern of the lesson on writing files. It loads a file that does not exist, saves two tasks, reads the file back and prints the contents of the folder.
The file check.js:
vi check.js
const { mkdtemp, readFile, readdir, rm, writeFile } = require('node:fs/promises');
const { tmpdir } = require('node:os');
const { join } = require('node:path');
const { Task } = require('./src/task');
const { load, save } = require('./src/storage');
async function main() {
const folder = await mkdtemp(join(tmpdir(), 'tasks-'));
const file = join(folder, 'tasks.json');
try {
const empty = await load(file);
console.log('a missing file loads as ' + empty.length + ' task(s)');
const tasks = [new Task(1, 'write the model'), new Task(2, 'read the JSON file')];
console.log('saved ' + (await save(file, tasks)) + ' task(s)');
const text = await readFile(file, 'utf8');
console.log('the file has ' + (text.match(/\n/g) || []).length + ' lines');
console.log('the folder holds: ' + (await readdir(folder)).join(', '));
const back = await load(file);
console.log('loaded: ' + back.map((task) => task.title).join(' | '));
console.log('a task came back: ' + (back[0] instanceof Task));
await writeFile(file, '{"version": 1}\n');
try {
await load(file);
} catch (error) {
console.log('a file without tasks says: ' + error.message);
}
} finally {
await rm(folder, { force: true, recursive: true });
}
}
main().catch((error) => {
console.error('error: ' + error.message);
process.exitCode = 1;
});
node check.js
a missing file loads as 0 task(s)
saved 2 task(s)
the file has 15 lines
the folder holds: tasks.json
loaded: write the model | read the JSON file
a task came back: true
a file without tasks says: the file has no tasks array
The missing file gave an empty array, the save returned the number of tasks it wrote, and the folder holds: tasks.json is the proof that the rename happened: a temporary file would still be listed beside the target. The loaded titles came back in the order of the file, and back[0] instanceof Task is true, which is the difference between reading JSON and reading a task list.
A file that is not a task list
Two things can be wrong with a file: it is not JSON at all, or it is JSON with the wrong shape. The first one is caught by JSON.parse and arrives as a SyntaxError with the position in its message, and the second one needs a check of its own, because undefined.map is a TypeError that says nothing about the file.
The check overwrites the good file with {"version": 1} and loads it. The message that comes back names the field that is missing, which is the message a reader of a broken file needs; the same file with a trailing comma would give the SyntaxError instead, and both are shown by the programs of the lesson on JSON.
Exercises
- Read the version field and throw an error when it is not 1. Which line of the check would show the new message?
- Write the file with no indentation and compare the size with the report of the current format. How many bytes does the indentation cost for two tasks?
- Make the save remove the temporary file when the write fails, with a try and a finally. Which folder would a test need to make the write fail?
- Save an empty list and load it again. What does the file hold, and is an empty list different from a file that is not there?
- Replace the rename with a direct write to tasks.json and kill the program with Ctrl-C during a long save. What can the file hold, and why does the test not see it?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does the save write a temporary file and rename it?
Answer
A rename is one step, so a reader never sees half a file
The old file stays readable until the new one is complete, and the swap is atomic inside one folder.
-
What does this program print?
const data = { version: 1, tasks: [] }; console.log(Object.keys(data).join(","), Array.isArray(data.tasks));Answer
version,tasks true
The keys keep the order of the object, and the tasks field is an array.
-
Which error code means that a file is not there?
Answer
ENOENT
The name is short for "error, no entity", and it is the one code the loader treats as an empty list.
-
What does this program print?
const text = '{"version": 1}'; const data = JSON.parse(text); console.log(data.tasks === undefined, typeof data.version);Answer
true number
The file has no tasks field, and a JSON number becomes a number.
-
Why is catching every read error and returning an empty list wrong?
Answer
A file that exists but cannot be read would look like an empty tracker and be overwritten
The next save would replace a file that is only unreadable with a list of no tasks.
-
What does this program print?
try { JSON.parse("{ \"version\": 1, }"); } catch (error) { console.log(error.name); }Answer
SyntaxError
A trailing comma is a syntax error for a JSON parser.
-
What does
JSON.stringify(data, null, 2)change about the text?Answer
It puts each field on its own line with two spaces of indentation
The third argument is the indentation, and the second one is a replacer that is not used here.
-
What does this program print?
const path = "tasks.json.tmp"; console.log(path.split(".").pop(), path.endsWith(".tmp"));Answer
tmp true
The last part after a dot is the extension of the temporary file.
-
What does the save return in this project?
Answer
The number of tasks it wrote
The count is what the check prints, and it is cheap to return from a function that already has the array.
-
Where must the temporary file be for the rename to be atomic?
Answer
In the same folder as the target file
Across two file systems a rename becomes a copy and a delete, and the guarantee is gone.
The programs on this page were run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev