Capstone A: the tracker in one listing
The tracker is finished and the last lesson of project A reads it. Nothing is added here: the eight files below are the state the previous five lessons reached, and the lesson is a review of the whole program one file at a time, with the reason for each split and the change that the file went through.
The project starts as a folder with a manifest, a lint config, a model and a check program, and it ends as a package with a command, a storage, a module of commands and two test files. The check program is gone because the command line took its place, which is the only file of the project that was removed rather than changed.
The files and what each one owns
Each file answers one question and no file answers two. The model knows what a task is, the storage knows what the file is, the commands know what the four words do to a list, and the command line knows about arguments, streams and statuses. A change to the file format touches one file, and a change to the help text touches one other.
The folder tasks:
tasks/
bin/tasks.js arguments, streams, statuses
src/commands.js the four commands over a list
src/storage.js the JSON file
src/task.js one task and its errors
test/storage.test.js
test/task.test.js
eslint.config.js
package.json
The manifest has not changed since lesson 124 and the lint config has not changed either, which is worth saying: the two files that a project starts with are usually the two that nobody touches again.
The file package.json:
{
"name": "tasks",
"version": "1.0.0",
"description": "A task tracker that keeps its list in a JSON file",
"type": "commonjs",
"scripts": {
"test": "node --test --test-reporter=dot",
"lint": "eslint ."
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"eslint": "^10.14.0"
}
}
The file eslint.config.js:
const js = require('@eslint/js');
module.exports = [
js.configs.recommended,
{
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'commonjs',
globals: {
console: 'readonly',
process: 'readonly',
},
},
},
];
The import order of the files is the order of the dependencies: bin requires src/commands and src/storage, the commands require the model, and the storage requires the model and the file system. Nothing requires the command line and nothing requires a test, which is the shape of a program that can be read from the outside in.
The model
The model was the first file of the project and it has not changed since. It holds a constant, an error class and a class with three fields, four checks, two methods and a static loader, and it imports nothing at all: no file system, no console and no process. That independence is why its five tests need no setup.
The file src/task.js:
const MAX_TITLE = 60;
class TaskError extends Error {
constructor(message) {
super(message);
this.name = 'TaskError';
}
}
class Task {
constructor(id, title, done = false) {
if (!Number.isInteger(id) || id < 1) {
throw new TaskError('id must be a positive integer, got ' + id);
}
if (typeof title !== 'string' || title.trim() === '') {
throw new TaskError('title must be a non-empty string');
}
if (title.trim().length > MAX_TITLE) {
throw new TaskError('title is longer than ' + MAX_TITLE + ' characters');
}
if (typeof done !== 'boolean') {
throw new TaskError('done must be a boolean, got ' + typeof done);
}
this.id = id;
this.title = title.trim();
this.done = done;
}
complete() {
return new Task(this.id, this.title, true);
}
toJSON() {
return { id: this.id, title: this.title, done: this.done };
}
static fromJSON(data) {
return new Task(data.id, data.title, data.done);
}
}
module.exports = { MAX_TITLE, Task, TaskError };
complete returns a new task rather than changing the old one, and fromJSON goes through the constructor rather than around it. The two decisions are the whole design of the file: a task is valid by construction, and a list of tasks is a list of values that can be copied.
The storage
The storage knows two functions and one format. It was written in lesson 125 and it has not changed since either, which is the reward for keeping the file format in one place: the commands of lesson 126 and the polish of lesson 128 both worked on the array and neither had to know that the array came from a file.
The file 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 };
The save returns a count and the load returns an array, so the two functions have the shape of a repository: no printing, no exit code and no question about which file. The name of the file arrives as an argument, which is why the tests of the previous lesson could give every case a folder of its own.
The commands and the command line
The module of commands is the file that changed most, and both changes went in the same direction: the knowledge of the arguments moved out of the command line. Lesson 126 wrote the parser and the four functions, and lesson 128 added the usage text, the two checks of the parser and the summary line.
The file src/commands.js:
const { Task, TaskError } = require('./task');
const USAGE = [
'usage: node bin/tasks.js <command> [argument]',
'',
' add <title> add a task',
' list print every task and a summary',
' done <id> mark a task as done',
' remove <id> remove a task',
' help print this text',
].join('\n');
function parse(argv) {
const [name, ...rest] = argv;
if (name === 'help' || name === '--help' || name === '-h') {
return { type: 'help' };
}
if (name === 'add') {
const title = rest.join(' ').trim();
if (title === '') {
return { type: 'usage', message: 'add needs a title' };
}
return { type: 'add', title };
}
if (name === 'list') {
return { type: 'list' };
}
if (name === 'done' || name === 'remove') {
const id = Number(rest[0]);
if (rest.length !== 1 || !Number.isInteger(id) || id < 1) {
return { type: 'usage', message: name + ' takes one task id' };
}
return { type: name, id };
}
return { type: 'usage', message: name === undefined ? 'no command given' : 'unknown command: ' + name };
}
function find(tasks, id) {
const task = tasks.find((entry) => entry.id === id);
if (task === undefined) {
throw new TaskError('no task with id ' + id);
}
return task;
}
function add(tasks, title) {
const id = tasks.reduce((highest, task) => Math.max(highest, task.id), 0) + 1;
return tasks.concat(new Task(id, title));
}
function complete(tasks, id) {
find(tasks, id);
return tasks.map((task) => (task.id === id ? task.complete() : task));
}
function remove(tasks, id) {
find(tasks, id);
return tasks.filter((task) => task.id !== id);
}
function render(tasks) {
if (tasks.length === 0) {
return 'no tasks';
}
return tasks
.map((task) => task.id + '. [' + (task.done ? 'x' : ' ') + '] ' + task.title)
.join('\n');
}
function summary(tasks) {
const done = tasks.filter((task) => task.done).length;
return tasks.length + ' task(s), ' + done + ' done';
}
module.exports = { USAGE, add, complete, parse, remove, render, summary };
The command line changed with it and stayed short. Lesson 128 gave it the help action, the usage branch with its status and the summary line after a change, and the rest of the file kept the shape that lesson 126 gave it.
The file bin/tasks.js:
#!/usr/bin/env node
const { load, save } = require('../src/storage');
const { USAGE, add, complete, parse, remove, render, summary } = require('../src/commands');
const FILE = 'tasks.json';
async function main() {
const action = parse(process.argv.slice(2));
if (action.type === 'help') {
console.log(USAGE);
return;
}
if (action.type === 'usage') {
console.error('error: ' + action.message);
console.error(USAGE);
process.exitCode = 2;
return;
}
const tasks = await load(FILE);
if (action.type === 'list') {
console.log(render(tasks));
console.log(summary(tasks));
return;
}
let next = tasks;
if (action.type === 'add') {
next = add(tasks, action.title);
console.log('added the task ' + next[next.length - 1].id);
}
if (action.type === 'done') {
next = complete(tasks, action.id);
console.log('task ' + action.id + ' is done');
}
if (action.type === 'remove') {
next = remove(tasks, action.id);
console.log('removed the task ' + action.id);
}
await save(FILE, next);
console.log(summary(next));
}
main().catch((error) => {
console.error('error: ' + error.message);
process.exitCode = 1;
});
The shebang is the line that lets an operating system run the file directly, and it is there although the lessons type node bin/tasks.js. The lesson on bin and npx shows the day it matters: the same file with a bin field in the manifest becomes a command named tasks.
The tests
Ten tests in two files cover the two modules that hold a decision. The four checks of the model, the copy that complete returns, the JSON round trip, the missing file, the temp-free write and the two refusals of the loader are all the tests the project needs, and a change that breaks one of the decisions breaks a test.
The file test/task.test.js:
const test = require('node:test');
const assert = require('node:assert/strict');
const { Task, TaskError } = require('../src/task');
test('a task keeps its three fields', () => {
const task = new Task(3, ' write the model ');
assert.equal(task.id, 3);
assert.equal(task.title, 'write the model');
assert.equal(task.done, false);
});
test('a task refuses an id that is not a positive integer', () => {
assert.throws(() => new Task(0, 'x'), TaskError);
assert.throws(() => new Task(1.5, 'x'), /positive integer/);
});
test('a task refuses an empty title', () => {
assert.throws(() => new Task(1, ' '), /non-empty/);
assert.throws(() => new Task(1, 'x'.repeat(61)), /60 characters/);
});
test('complete returns a new task and leaves the old one alone', () => {
const task = new Task(1, 'a');
const done = task.complete();
assert.equal(done.done, true);
assert.equal(task.done, false);
assert.notEqual(done, task);
});
test('a task survives the JSON round trip', () => {
const task = new Task(7, 'keep the order', true);
assert.deepEqual(Task.fromJSON(task.toJSON()), task);
});
The file test/storage.test.js:
const test = require('node:test');
const assert = require('node:assert/strict');
const { mkdtemp, 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 withFolder(run) {
const folder = await mkdtemp(join(tmpdir(), 'tasks-test-'));
try {
await run(folder);
} finally {
await rm(folder, { force: true, recursive: true });
}
}
test('a missing file loads as an empty list', () =>
withFolder(async (folder) => {
assert.deepEqual(await load(join(folder, 'tasks.json')), []);
}));
test('what is saved comes back with its fields', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
const tasks = [new Task(1, 'one'), new Task(2, 'two', true)];
assert.equal(await save(file, tasks), 2);
assert.deepEqual(await load(file), tasks);
}));
test('the write leaves no temporary file', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
await save(file, [new Task(1, 'one')]);
assert.deepEqual(await readdir(folder), ['tasks.json']);
}));
test('a file without a tasks array is refused', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
await writeFile(file, '{"version": 1}\n');
await assert.rejects(load(file), /no tasks array/);
}));
test('a broken file keeps the error of JSON', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
await writeFile(file, 'not json\n');
await assert.rejects(load(file), SyntaxError);
}));
The command line has no test of its own here, and that is a decision rather than an oversight: a test of the command line has to start a process, give it arguments and read three streams, which is the work of the exercises. The functions it calls are tested, and the session below is the check of the rest.
The whole tracker
The session starts in a folder without a task file and ends with the file itself on the screen. Two tasks are added, the first is completed, the second is removed, and the tests and the linter run on the same state.
node bin/tasks.js add write the model
node bin/tasks.js add ship the tracker
node bin/tasks.js done 1
node bin/tasks.js list
node bin/tasks.js remove 2
node bin/tasks.js list
cat tasks.json
node --test --test-reporter=dot
echo "the exit status: $?"
npx eslint .
echo "the lint status: $?"
added the task 1
1 task(s), 0 done
added the task 2
2 task(s), 0 done
task 1 is done
2 task(s), 1 done
1. [x] write the model
2. [ ] ship the tracker
2 task(s), 1 done
removed the task 2
1 task(s), 1 done
1. [x] write the model
1 task(s), 1 done
{
"version": 1,
"tasks": [
{
"id": 1,
"title": "write the model",
"done": true
}
]
}
..........
the exit status: 0
the lint status: 0
The file that the last cat prints holds one task, with the version around it and the two-space indentation of the storage. The ten dots are the ten tests, and the two zeros are the answers of the test runner and of the linter.
That is project A. The next lesson starts project B, which is the same discipline with a different value: text instead of a task, and a map instead of a list.
Exercises
- Add a test that runs the command line with spawnSync and checks the status of a wrong call. How many lines does the test need, and what does it have to remove afterwards?
- Move the file name from bin/tasks.js into an environment variable with a default. Which two files change, and why is the default the same value as before?
- Add a search module that reads the file and answers a text query. Which layer does it belong to, and which file would call it?
- Change the format of a task to hold a created date and keep the old files readable. Which function reads the version field, and what does it do with a file that has none?
- Write the same tracker with an array of strings instead of a class and list the checks that disappear. Which of them would come back as a bug report?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which file of the tracker knows about the arguments, the streams and the statuses?
Answer
bin/tasks.js
The command line is the only place that talks to the outside, which keeps the rest testable.
-
What does this program print?
const files = ["task.js", "storage.js", "commands.js"]; console.log(files.map((file) => file.replace(".js", "")).join(" "));Answer
task storage commands
The replace drops the extension of each name and the join puts a space between them.
-
Which file was removed between lesson 124 and the end of the project?
Answer
The check program, because the command line took its place
A check program is a scaffold: it is useful while there is no program to run, and then it is noise.
-
What does this program print?
const { save } = { save: (tasks) => tasks.length }; console.log(save([{}, {}]));Answer
2
The function returns the length of the array it received.
-
Why does the storage take the file name as an argument?
Answer
So a test can give every case a folder of its own
A function of its inputs is testable; a function that reads a fixed path is not.
-
What does this program print?
const task = { id: 1, done: true }; const copy = { ...task, done: false }; console.log(task.done, copy.done);Answer
true false
The spread copies the fields and the later value wins in the copy only.
-
Which two files does the project start with and never change again?
Answer
package.json and eslint.config.js
The manifest and the lint config describe the project rather than the program.
-
What does this program print?
const lines = ["1. [x] a", "2. [ ] b"]; console.log(lines.filter((line) => line.includes("[x]")).length);Answer
1
Only one line holds the box of a done task.
-
Why do the tests of the storage not need a mock file system?
Answer
A temporary folder is a real file system and costs nothing to make
The real functions run against a folder that is removed afterwards, so the test checks the real bytes.
-
What does this program print?
const require_order = ["bin", "commands", "task"]; console.log(require_order[require_order.length - 1]);Answer
task
The last entry of the array is the one at the length minus one.
The programs and commands 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