These are the notes for JavaScript episode 33, a project episode. There is no new syntax today. Instead we build one real program, a to-do app that runs in the terminal, and every step breaks first so you can see why each piece is needed. Version 1 keeps tasks in an array, and the second launch says No tasks yet. Saving to a JSON file crashes on the very first launch with ENOENT. Catching only ENOENT fixes it. done 5 crashes with TypeError: Cannot set properties of undefined, so we validate task numbers and return new arrays (pure functions). Then we split the app into three modules, test it with node:test, and read real commands from process.argv. Every output below is real Node.js output (Node 24). Long stack traces are shortened with ..., and folder paths are shortened to the file name where they would only add noise. Test timings in brackets, like (1.48ms), change on every run.
Builds on: arrays and push/forEach (episode 7), objects (8), functions and arrow functions (9), map and filter (11), destructuring, spread and rest (12), try/catch, throw and RangeError (13), the quiz-game project (15), modules with require/module.exports (18), JSON (19), pure functions and immutability (29), testing with node:test (30). Leads to: DSA in JavaScript 1: arrays, stacks and queues (34).
The real-life idea: Asha's sticky notes
Asha keeps her tasks on sticky notes on the fridge: buy milk, pay the electricity bill, book train tickets. Notes fall off. Last month the electricity-bill note disappeared and she paid a late fee. She works at her laptop all day anyway, so she wants a tiny app she can type into:
node todo.js add Buy milk
A program you use by typing commands in a terminal is called a CLI, a command line interface (as opposed to a GUI, a graphical user interface with buttons and windows). git, npm and node itself are all CLIs. The single most important feature of Asha's app: the tasks must still be there tomorrow.
| Asha's life | The app |
|---|---|
| a sticky note | one task object: { text: "Buy milk", done: false } |
| all the notes on the fridge | an array of tasks, todos |
| writing a new note | the add command |
| ticking a note | the done command |
| throwing a note away | the remove command |
| reading all the notes | the list command |
| notes falling off the fridge | data lost when the program ends |
| a diary in the drawer | a file on disk, todos.json |
What we're building
| Command | What it does | Example |
|---|---|---|
add <text> |
adds a task at the end | node todo.js add Buy milk |
list |
prints every task with its number | node todo.js list |
done <n> |
marks task number n as done |
node todo.js done 2 |
remove <n> |
deletes task number n |
node todo.js remove 1 |
Task numbers start at 1 for humans; array indexes start at 0, so task n lives at index n - 1.
Version 1: tasks in an array
startApp(commands) stands for one launch of the app. It receives a list of command strings, like "add Buy milk", and keeps tasks in an array. (In the online compiler every Run starts a fresh program, so calling startApp twice in one run is how we pretend the app was opened on Monday and again on Tuesday.)
function startApp(commands) {
const todos = [];
for (const line of commands) {
const [cmd, ...words] = line.split(" ");
const text = words.join(" ");
if (cmd === "add") todos.push({ text, done: false });
if (cmd === "list") {
if (todos.length === 0) console.log("No tasks yet");
todos.forEach((t, i) => console.log(`${i + 1}. [${t.done ? "x" : " "}] ${t.text}`));
}
}
}
console.log("--- Monday ---");
startApp(["add Buy milk", "add Pay electricity bill", "list"]);
console.log("--- Tuesday ---");
startApp(["list"]);
--- Monday ---
1. [ ] Buy milk
2. [ ] Pay electricity bill
--- Tuesday ---
No tasks yet
How one command line is taken apart:
line.split(" ")turns"add Buy milk"into["add", "Buy", "milk"].const [cmd, ...words] = ...is destructuring with rest (episode 12):cmdgets"add",wordscollects the rest,["Buy", "milk"].words.join(" ")glues the words back together:"Buy milk".{ text, done: false }is shorthand for{ text: text, done: false }.- In the list line,
i + 1turns the index into a human task number, andt.done ? "x" : " "(the ternary operator, episode 5) prints[x]for a done task and[ ]otherwise.
Why Tuesday is empty: todos lives in memory (RAM). A program's memory is wiped when it ends, so every launch starts again from const todos = []. That's the sticky note falling off, in code.
The whiteboard and the diary: memory vs a file
| In Asha's flat | In a program |
|---|---|
| a kitchen whiteboard, wiped every night | variables in memory: fast, gone when the program ends |
| a diary in the drawer, still there next week | a file on disk: slower, survives restarts, even a reboot |
| writing in a neat, fixed format so you can read it back | JSON: JSON.stringify to write, JSON.parse to read |
Saving data so it outlives the program is called persistence. A file is the simplest kind; databases are the next step up.
Version 2: save and load, and the first-run crash
Node's built-in node:fs (file system) module reads and writes files.
fs.readFileSync(FILE, "utf8")reads the whole file and returns its text (a string)."utf8"is the text encoding; without it you'd get aBufferof raw bytes.JSON.parse(text)turns that text back into an array of objects.JSON.stringify(todos, null, 2)turns the array into text. Thenullmeans "no replacer function", and2means "indent with 2 spaces", so the file is readable by a human.fs.writeFileSync(FILE, text)writes the text, creating the file if needed and replacing what was there.
const fs = require("node:fs");
const FILE = "todos.json";
function load() {
return JSON.parse(fs.readFileSync(FILE, "utf8"));
}
function save(todos) {
fs.writeFileSync(FILE, JSON.stringify(todos, null, 2));
}
function startApp(commands) {
const todos = load();
for (const line of commands) {
const [cmd, ...words] = line.split(" ");
const text = words.join(" ");
if (cmd === "add") todos.push({ text, done: false });
if (cmd === "list") {
if (todos.length === 0) console.log("No tasks yet");
todos.forEach((t, i) => console.log(`${i + 1}. [${t.done ? "x" : " "}] ${t.text}`));
}
}
save(todos);
}
console.log("--- Monday ---");
startApp(["add Buy milk", "add Pay electricity bill", "list"]);
console.log("--- Tuesday ---");
startApp(["list"]);
--- Monday ---
node:fs:483
return binding.readFileUtf8(path, stringToFlags(options.flag));
^
Error: ENOENT: no such file or directory, open 'todos.json'
at Object.readFileSync (node:fs:483:20)
at load (main.js:4:24)
at startApp (main.js:10:17)
...
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'todos.json'
}
It crashed before Monday could print a single task. On the very first launch nobody has saved anything yet, so there is no file to read. ENOENT is the operating system's error code for "Error: NO ENTry", meaning no such file or directory. Notice that the error object carries extra fields: code: 'ENOENT', syscall: 'open' and path: 'todos.json'. We'll use code in a moment.
Version 3: catch only ENOENT
load wraps the read in try/catch. If the error's code is ENOENT, it's simply the first run, so we return an empty list. Any other error is thrown again (throw err), because we only want to handle the one problem we expected.
const fs = require("node:fs");
const FILE = "todos.json";
function load() {
try {
return JSON.parse(fs.readFileSync(FILE, "utf8"));
} catch (err) {
if (err.code === "ENOENT") return [];
throw err;
}
}
function save(todos) {
fs.writeFileSync(FILE, JSON.stringify(todos, null, 2));
}
function startApp(commands) {
const todos = load();
for (const line of commands) {
const [cmd, ...words] = line.split(" ");
const text = words.join(" ");
if (cmd === "add") todos.push({ text, done: false });
if (cmd === "list") {
if (todos.length === 0) console.log("No tasks yet");
todos.forEach((t, i) => console.log(`${i + 1}. [${t.done ? "x" : " "}] ${t.text}`));
}
}
save(todos);
}
console.log("--- Monday ---");
startApp(["add Buy milk", "add Pay electricity bill", "list"]);
console.log("--- Tuesday ---");
startApp(["list"]);
console.log(fs.readFileSync(FILE, "utf8"));
--- Monday ---
1. [ ] Buy milk
2. [ ] Pay electricity bill
--- Tuesday ---
1. [ ] Buy milk
2. [ ] Pay electricity bill
[
{
"text": "Buy milk",
"done": false
},
{
"text": "Pay electricity bill",
"done": false
}
]
Tuesday's launch found the file Monday's launch saved. The last block is the file itself: plain, indented JSON you could open in any editor.
Why not use fs.existsSync(FILE) first? You can (if (!fs.existsSync(FILE)) return [];), and it works for a simple app. But checking first and reading second leaves a tiny gap where the file could be deleted in between; trying the read and handling ENOENT is the more robust pattern, and it's what you'll see in real Node code.
The done command: a crash, then a pure and safe fix
Each command becomes its own small function. addTask returns a new array with spread (episode 12). The first attempt at markDone changes task n directly:
function addTask(todos, text) {
return [...todos, { text, done: false }];
}
function markDone(todos, n) {
todos[n - 1].done = true;
return todos;
}
let todos = addTask([], "Buy milk");
todos = addTask(todos, "Pay electricity bill");
todos = markDone(todos, 2);
console.log(todos);
todos = markDone(todos, 5);
[
{ text: 'Buy milk', done: false },
{ text: 'Pay electricity bill', done: true }
]
main.js:5
todos[n - 1].done = true;
^
TypeError: Cannot set properties of undefined (setting 'done')
at markDone (main.js:5:21)
at Object.<anonymous> (main.js:12:9)
...
There are only two tasks, so todos[4] doesn't exist: it is undefined, and you can't set a property on undefined. One typo by the user crashes the whole app. And there's a second problem: markDone mutated (changed) the array it was given, the mutation trap from episode 29.
The fix does two things:
- Validate
nfirst. If it isn't a whole number, is less than 1, or is bigger than the number of tasks, throw aRangeError(episode 13) with a clear message.Number.isIntegeralso rejects text:Number("two")isNaN, andNumber.isInteger(NaN)isfalse. - Don't mutate.
mapbuilds a new array: the matching task is copied withdone: true({ ...t, done: true }), every other task is kept as it is. NowmarkDoneis a pure function: same input, same output, nothing outside changed.
function addTask(todos, text) {
return [...todos, { text, done: false }];
}
function markDone(todos, n) {
if (!Number.isInteger(n) || n < 1 || n > todos.length) {
throw new RangeError(`No task number ${n}`);
}
return todos.map((t, i) => (i === n - 1 ? { ...t, done: true } : t));
}
let todos = addTask([], "Buy milk");
todos = addTask(todos, "Pay electricity bill");
todos = markDone(todos, 2);
console.log(todos);
try {
todos = markDone(todos, 5);
} catch (err) {
console.log(err.message);
}
[
{ text: 'Buy milk', done: false },
{ text: 'Pay electricity bill', done: true }
]
No task number 5
A friendly message instead of a crash, and the app stays alive. The rule: never trust user input. Anything typed by a person (or read from a file, or sent over the network) must be checked before you use it.
removeTask and format
removeTask works the same way, with filter instead of map: keep every task whose index is not n - 1. The number check is shared, so it moves into a small helper, check. format turns the list into the text we print, and returns "No tasks yet" for an empty list. It returns text instead of printing it, so it stays pure and testable.
function check(todos, n) {
if (!Number.isInteger(n) || n < 1 || n > todos.length) {
throw new RangeError(`No task number ${n}`);
}
}
function removeTask(todos, n) {
check(todos, n);
return todos.filter((t, i) => i !== n - 1);
}
function format(todos) {
if (todos.length === 0) return "No tasks yet";
return todos.map((t, i) => `${i + 1}. [${t.done ? "x" : " "}] ${t.text}`).join("\n");
}
In filter((t, i) => ...) we don't use t, only the index i, but the index is the second parameter, so t must still be written. (Some people name an unused parameter _.)
Splitting into modules: three files, three jobs
The code is getting long, so we split it into three files (modules, episode 18), each with one job:
| File | Job | Touches the disk? | Prints? |
|---|---|---|---|
tasks.js |
pure functions: addTask, markDone, removeTask, format |
no | no |
store.js |
load and save for todos.json |
yes, the only file that does | no |
todo.js |
the glue: read the command, call the right function, save, print | via store.js |
yes |
todo.js ──require──▶ tasks.js (data in, data out)
│
└─────require──▶ store.js (todos.json on disk)
This idea, keeping logic, storage and input/output apart, is called separation of concerns. It pays off immediately: tasks.js can be tested without any files, and if Asha later wants a database instead of a JSON file, only store.js changes.
The complete project
tasks.js
function addTask(todos, text) {
if (text.trim() === "") throw new Error("Task text is empty");
return [...todos, { text, done: false }];
}
function check(todos, n) {
if (!Number.isInteger(n) || n < 1 || n > todos.length) {
throw new RangeError(`No task number ${n}`);
}
}
function markDone(todos, n) {
check(todos, n);
return todos.map((t, i) => (i === n - 1 ? { ...t, done: true } : t));
}
function removeTask(todos, n) {
check(todos, n);
return todos.filter((t, i) => i !== n - 1);
}
function format(todos) {
if (todos.length === 0) return "No tasks yet";
return todos.map((t, i) => `${i + 1}. [${t.done ? "x" : " "}] ${t.text}`).join("\n");
}
module.exports = { addTask, markDone, removeTask, format };
addTask also refuses an empty task: text.trim() removes spaces from both ends, so " " counts as empty too. check is not exported: it's a private helper of this module.
store.js
const fs = require("node:fs");
const FILE = "todos.json";
function load() {
try {
return JSON.parse(fs.readFileSync(FILE, "utf8"));
} catch (err) {
if (err.code === "ENOENT") return [];
throw err;
}
}
function save(todos) {
fs.writeFileSync(FILE, JSON.stringify(todos, null, 2));
}
module.exports = { load, save };
"todos.json" is a relative path: it's looked up in the folder you ran node from (the current working directory), not necessarily the folder of store.js. That's fine for this app; to always use the script's folder you'd write path.join(__dirname, "todos.json") with require("node:path").
todo.js
const { addTask, markDone, removeTask, format } = require("./tasks");
const { load, save } = require("./store");
const [cmd, ...words] = process.argv.slice(2);
const text = words.join(" ");
let todos = load();
try {
if (cmd === "add") todos = addTask(todos, text);
else if (cmd === "done") todos = markDone(todos, Number(text));
else if (cmd === "remove") todos = removeTask(todos, Number(text));
else if (cmd !== "list") throw new Error(`Unknown command: ${cmd}`);
save(todos);
console.log(format(todos));
} catch (err) {
console.log(`Error: ${err.message}`);
process.exitCode = 1;
}
require("./tasks"): the./means "a file in this folder";.jscan be left out.- Each command replaces
todoswith the new array the pure function returns (that's why it'slet). - Anything else than the four commands throws
Unknown command. - If anything throws, the
catchprints a friendly message and setsprocess.exitCode = 1.
Reading the command: process.argv
How does the program see the words you typed? Through process.argv, the argument vector: an array of strings.
console.log(process.argv);
console.log(process.argv.slice(2));
$ node argv.js add Buy milk
[
'/root/node24/node_modules/node/bin/node',
'/home/claude/todo/argv.js',
'add',
'Buy',
'milk'
]
[ 'add', 'Buy', 'milk' ]
Index 0 is the path to the node program, index 1 is the path to your script, and from index 2 on come the words you typed, split at spaces by the terminal. So process.argv.slice(2) is exactly our command. Every item is a string, even "3", which is why todo.js uses Number(text). To pass several words as one argument, quote them in the terminal: node todo.js add "Buy milk" gives [ 'add', 'Buy milk' ]; our join(" ") handles both ways.
Exit codes
When a program ends it hands the terminal a number, its exit code: 0 means success, anything else means failure. Scripts, CI servers and tools like npm read it. process.exitCode = 1 sets the code but lets the program finish normally (better than process.exit(1), which stops immediately, possibly before output is written). In a terminal, echo $? shows the last exit code.
A real session
Run in an empty folder containing the three files:
$ node todo.js list
No tasks yet
(exit code 0)
$ node todo.js add Buy milk
1. [ ] Buy milk
(exit code 0)
$ node todo.js add Pay electricity bill
1. [ ] Buy milk
2. [ ] Pay electricity bill
(exit code 0)
$ node todo.js add Book train tickets
1. [ ] Buy milk
2. [ ] Pay electricity bill
3. [ ] Book train tickets
(exit code 0)
$ node todo.js done 2
1. [ ] Buy milk
2. [x] Pay electricity bill
3. [ ] Book train tickets
(exit code 0)
$ node todo.js done two
Error: No task number NaN
(exit code 1)
$ node todo.js remove 5
Error: No task number 5
(exit code 1)
$ node todo.js remove 1
1. [x] Pay electricity bill
2. [ ] Book train tickets
(exit code 0)
$ node todo.js add
Error: Task text is empty
(exit code 1)
$ node todo.js fly
Error: Unknown command: fly
(exit code 1)
$ cat todos.json
[
{
"text": "Pay electricity bill",
"done": true
},
{
"text": "Book train tickets",
"done": false
}
]
(The (exit code ...) lines were printed with echo "(exit code $?)" after each command.) Notice that a failed command doesn't save anything: save(todos) is inside the try, after the line that threw, so a bad command never damages the file.
Testing the pure functions with node:test
Because tasks.js is pure (no files, no printing), testing it is just "call it, compare the result" (episode 30). tasks.test.js:
const test = require("node:test");
const assert = require("node:assert");
const { addTask, markDone, removeTask } = require("./tasks");
test("add puts a new task at the end", () => {
assert.deepStrictEqual(addTask([], "Buy milk"), [{ text: "Buy milk", done: false }]);
});
test("done marks only that task", () => {
const todos = addTask(addTask([], "Buy milk"), "Pay bill");
assert.deepStrictEqual(markDone(todos, 2)[1], { text: "Pay bill", done: true });
assert.strictEqual(todos[1].done, false);
});
test("done with a wrong number throws", () => {
assert.throws(() => markDone([], 5), RangeError);
});
$ node --test
✔ add puts a new task at the end (1.483268ms)
✔ done marks only that task (0.519764ms)
✔ done with a wrong number throws (0.405626ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 175.435647
deepStrictEqualbecause we compare arrays and objects (episode 30).- The second test also checks
todos[1].doneis stillfalse: the original array was not changed. If someone brings back the mutating version, this test turns red. assert.throwsgets a function() => markDone([], 5), not a call.
In the video the same functions and tests were in one main.js in the online compiler, with the same three ticks. In a real project, add "scripts": { "test": "node --test" } to package.json and run npm test before every commit.
What if todos.json gets broken?
Asha opens todos.json in an editor and accidentally leaves it as {oops:
$ node todo.js list
store.js:9
throw err;
^
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
at JSON.parse (<anonymous>)
at load (store.js:6:17)
at Object.<anonymous> (todo.js:6:13)
...
Node.js v24.22.2
load only catches ENOENT, so this SyntaxError is thrown again, loudly, and the program exits with code 1. That is on purpose. If load caught every error and returned [], the next add would save over her file with a one-task list, and every old task would be gone forever. A loud error is better than silent data loss. (An empty file gives a different message: Unexpected end of JSON input.) A friendlier version could catch the SyntaxError too, but then it should refuse to save and tell the user which file to fix, never quietly start fresh.
The whole build in one table
| Step | What broke | Why | Fix |
|---|---|---|---|
| 1. array in memory | Tuesday: No tasks yet |
memory is wiped when the program ends | save to a file |
2. readFileSync + writeFileSync |
Error: ENOENT: no such file or directory, open 'todos.json' |
first launch, no file yet | catch err.code === "ENOENT", return [] |
3. todos[n - 1].done = true |
TypeError: Cannot set properties of undefined (setting 'done') |
there is no task number 5 | check + RangeError, return a new array with map |
| 4. one long file | hard to test and change | logic, storage, I/O mixed | tasks.js, store.js, todo.js |
| 5. no proof it works | a future change could break done |
nothing checks it | node:test on the pure functions |
| 6. commands in the code | Asha can't type them | no way in from the terminal | process.argv.slice(2) |
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
const todos = []; at every launch |
Tuesday: No tasks yet |
memory is wiped when the program ends | load() from a JSON file, save() at the end |
fs.readFileSync("todos.json", "utf8") on the first run |
Error: ENOENT: no such file or directory, open 'todos.json' |
nothing saved yet | catch err.code === "ENOENT" and return [] |
catch (err) { return []; } for every error |
a broken file is silently replaced, all tasks lost | caught too much | rethrow (throw err) what you didn't expect |
todos[n - 1].done = true with n = 5 |
TypeError: Cannot set properties of undefined (setting 'done') |
no task number 5 | check n, throw RangeError |
todos[n].done = true |
the wrong task gets ticked (task 3 for done 2) |
task numbers start at 1, indexes at 0 | use n - 1 |
comparing n === 2 with n from process.argv |
never true | argv items are strings: "2" |
Number(text) |
Number.isInteger left out |
done two → TypeError again |
Number("two") is NaN, and NaN < 1 is false |
!Number.isInteger(n) \|\| first |
fs.writeFileSync(FILE, todos) |
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Array |
writeFileSync writes text or bytes, not arrays |
JSON.stringify(todos, null, 2) |
fs.readFileSync(FILE) then JSON.parse |
works, but you got a Buffer, not a string |
no encoding given | pass "utf8" |
process.argv[0] as the command |
'/root/node24/node_modules/node/bin/node' |
0 is node, 1 is the script | process.argv.slice(2) |
require("tasks") |
Error: Cannot find module 'tasks' |
without ./ Node looks in node_modules |
require("./tasks") |
process.exit(1) inside catch |
works, but can cut off output that's still being written | stops immediately | process.exitCode = 1 |
Mini project: extend Asha's app
Try these yourself first; full solutions are in the Practice section.
edit 2 New text: change a task's text, keeping its done state.clear: remove every task that is done.- Tests for
removeTask: it removes only that task, doesn't change the original array, and throws for a bad number. - Due dates: tasks get a
duedate like"2026-11-08", and the list is sorted by it.
Practice
- Write
editTask(todos, n, text)and wire it intotodo.jsasedit <n> <text>. - Write
clearDone(todos)and aclearcommand. - Write at least three tests for
removeTask. - Add
addTaskDue(todos, text, due)that only accepts dates writtenYYYY-MM-DD, andsortByDue(todos)that returns a new, sorted array. - What does
node todo.js done 0print, and why?
Solutions
1, 2 and 4: a new module extra.js (we keep tasks.js exactly as in the video):
function check(todos, n) {
if (!Number.isInteger(n) || n < 1 || n > todos.length) {
throw new RangeError(`No task number ${n}`);
}
}
function editTask(todos, n, text) {
check(todos, n);
if (text.trim() === "") throw new Error("Task text is empty");
return todos.map((t, i) => (i === n - 1 ? { ...t, text } : t));
}
function clearDone(todos) {
return todos.filter((t) => !t.done);
}
function addTaskDue(todos, text, due) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(due)) throw new Error(`Bad date: ${due} (use YYYY-MM-DD)`);
return [...todos, { text, done: false, due }];
}
function sortByDue(todos) {
return [...todos].sort((a, b) => a.due.localeCompare(b.due));
}
function formatDue(todos) {
return todos.map((t, i) => `${i + 1}. [${t.done ? "x" : " "}] ${t.due} ${t.text}`).join("\n");
}
module.exports = { editTask, clearDone, addTaskDue, sortByDue, formatDue };
{ ...t, text }copies the task and replaces onlytext, sodoneis kept.sortByDuecopies with[...todos]first, becausesortchanges the array it's called on; the copy keeps the function pure.- Dates written
YYYY-MM-DDsort correctly as plain text:"2026-11-06" < "2026-11-08" < "2026-11-20". That's why the format is checked with a regular expression (episode 23):^\d{4}-\d{2}-\d{2}$means "4 digits, dash, 2 digits, dash, 2 digits, nothing else".
A quick check:
const { addTask, markDone, format } = require("./tasks");
const { editTask, clearDone, addTaskDue, sortByDue, formatDue } = require("./extra");
let todos = addTask(addTask([], "Buy milk"), "Pay bill");
todos = editTask(todos, 2, "Pay electricity bill");
todos = markDone(todos, 1);
console.log(format(todos));
console.log("--- clear ---");
console.log(format(clearDone(todos)));
console.log("--- due dates ---");
let trip = addTaskDue([], "Book train tickets", "2026-11-20");
trip = addTaskDue(trip, "Pay electricity bill", "2026-11-08");
trip = addTaskDue(trip, "Buy milk", "2026-11-06");
console.log(formatDue(sortByDue(trip)));
try {
addTaskDue(trip, "Diwali shopping", "8 Nov");
} catch (err) {
console.log(err.message);
}
1. [x] Buy milk
2. [ ] Pay electricity bill
--- clear ---
1. [ ] Pay electricity bill
--- due dates ---
1. [ ] 2026-11-06 Buy milk
2. [ ] 2026-11-08 Pay electricity bill
3. [ ] 2026-11-20 Book train tickets
Bad date: 8 Nov (use YYYY-MM-DD)
Wiring edit and clear into todo.js (two new lines and one new require):
const { addTask, markDone, removeTask, format } = require("./tasks");
const { editTask, clearDone } = require("./extra");
const { load, save } = require("./store");
const [cmd, ...words] = process.argv.slice(2);
const text = words.join(" ");
let todos = load();
try {
if (cmd === "add") todos = addTask(todos, text);
else if (cmd === "done") todos = markDone(todos, Number(text));
else if (cmd === "remove") todos = removeTask(todos, Number(text));
else if (cmd === "edit") todos = editTask(todos, Number(words[0]), words.slice(1).join(" "));
else if (cmd === "clear") todos = clearDone(todos);
else if (cmd !== "list") throw new Error(`Unknown command: ${cmd}`);
save(todos);
console.log(format(todos));
} catch (err) {
console.log(`Error: ${err.message}`);
process.exitCode = 1;
}
For edit 2 Pay electricity bill, words is ["2", "Pay", "electricity", "bill"]: the first word is the number, the rest is the new text.
$ node todo.js add Buy milk
1. [ ] Buy milk
$ node todo.js add Pay bill
1. [ ] Buy milk
2. [ ] Pay bill
$ node todo.js edit 2 Pay electricity bill
1. [ ] Buy milk
2. [ ] Pay electricity bill
$ node todo.js edit 7 Hello
Error: No task number 7
$ node todo.js done 1
1. [x] Buy milk
2. [ ] Pay electricity bill
$ node todo.js clear
1. [ ] Pay electricity bill
remove.test.js:
const test = require("node:test");
const assert = require("node:assert");
const { addTask, removeTask } = require("./tasks");
const two = addTask(addTask([], "Buy milk"), "Pay bill");
test("remove takes out only that task", () => {
assert.deepStrictEqual(removeTask(two, 1), [{ text: "Pay bill", done: false }]);
});
test("remove leaves the original array alone", () => {
removeTask(two, 1);
assert.strictEqual(two.length, 2);
});
test("remove with a wrong number throws", () => {
assert.throws(() => removeTask(two, 3), { name: "RangeError", message: "No task number 3" });
});
test("remove with text throws", () => {
assert.throws(() => removeTask(two, Number("two")), RangeError);
});
$ node --test remove.test.js
✔ remove takes out only that task (8.08255ms)
✔ remove leaves the original array alone (4.523807ms)
✔ remove with a wrong number throws (1.011559ms)
✔ remove with text throws (0.401959ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 340.272793
Error: No task number 0, with exit code 1.0is a whole number, butn < 1is true: task numbers start at 1. Without that check,todos[-1]would beundefinedand we'd be back to theTypeError.
Quick quiz
We run node app.js done 3. What does this print?
const [cmd, ...words] = process.argv.slice(2);
console.log(cmd, words);
- A.
done [ '3' ] - B.
node app.js - C.
done 3 - D.
[ 'done', '3' ] undefined
Answer
A. Real output:
done [ '3' ]
slice(2) skips the paths of node and the script, giving [ 'done', '3' ]. cmd takes the first item, and ...words collects the rest into an array of strings: [ '3' ]. The 3 is text, so use Number() before comparing or indexing.
Interview questions
- What is a CLI? A command line interface: a program you use by typing commands and arguments in a terminal, instead of clicking a GUI.
git,npmandnodeare CLIs. - How does a Node program read its command-line arguments?
process.argv, an array of strings:[0]is the node executable,[1]the script path, the rest are the arguments, soprocess.argv.slice(2). Libraries likecommanderor Node's built-inutil.parseArgshandle flags such as--due. - Why did the tasks disappear between runs, and how do you make data persist? Variables live in memory, which is freed when the process ends. Persist by writing to a file (JSON here) or a database, and reading it back at start-up.
- What does
ENOENTmean and how should you handle it? "No such file or directory". When a missing file is a normal situation (first run), catch the error, checkerr.code === "ENOENT", and use a default; rethrow every other error. - Why is catching every error and returning a default dangerous? It hides real problems. Here a corrupt
todos.jsonwould be silently replaced and all tasks lost. Catch only what you expect and can handle. - What does
JSON.stringify(value, null, 2)do? Converts the value to JSON text;nullmeans no replacer function,2indents with two spaces for readability. readFileSyncvsreadFile/fs.promises.readFile? The sync version blocks the thread until the file is read; fine for a small CLI that does one thing and exits, but a server should use the async versions (episodes 27-28) so it can keep serving others.- Why make
markDonereturn a new array instead of changing the old one? It becomes a pure function: predictable, easy to test, and no other code is surprised by a changed array (episode 29). - What is separation of concerns? How does this app use it? Each module has one job:
tasks.jslogic,store.jsstorage,todo.jsinput/output. Logic can be tested without files, and storage can be swapped without touching logic. - What is an exit code and why set it? The number a process returns to the shell: 0 success, non-zero failure. Scripts and CI use it to know whether a command worked. Prefer
process.exitCode = 1overprocess.exit(1). - How would you validate a user-typed number? Convert with
Number, then checkNumber.isInteger(n)and the allowed range, and give a clear error message. - What would you change to make this app safe if two commands ran at the same time? Both could read the old file and the last write would win. Real apps use a database, file locking, or write to a temporary file and rename it (an atomic write).
Glossary
| Term | Meaning | Example |
|---|---|---|
| CLI (command line interface) | a program you use by typing commands in a terminal | node todo.js add Buy milk |
| GUI | graphical user interface: windows and buttons | a phone to-do app |
| Terminal | the text window where you type commands | $ node todo.js list |
| Command / argument | the word that says what to do / the extra words it works on | done / 2 |
process.argv |
array of the command-line words, starting with node and the script | process.argv.slice(2) |
| Memory (RAM) | where variables live while a program runs; wiped when it ends | const todos = [] |
| Process | one running copy of a program | each node todo.js ... |
| Persistence | keeping data after the program ends | todos.json |
| File system | how the computer stores files and folders on disk | |
node:fs |
Node's built-in module for reading and writing files | require("node:fs") |
fs.readFileSync(path, "utf8") |
read a whole file as text, waiting until done | load() |
fs.writeFileSync(path, text) |
write text to a file, creating or replacing it | save() |
| Synchronous (sync) | the program waits for the operation to finish | readFileSync |
| UTF-8 | the standard text encoding; turns bytes into characters | "utf8" |
Buffer |
Node's object for raw bytes | readFileSync(FILE) without "utf8" |
| JSON | a text format for data: objects, arrays, strings, numbers, booleans | [{"text":"Buy milk","done":false}] |
JSON.stringify(v, null, 2) |
value → JSON text, indented by 2 spaces | |
JSON.parse(text) |
JSON text → value; throws SyntaxError on bad JSON |
|
ENOENT |
error code: no such file or directory | first run |
err.code |
a short code string on system errors | "ENOENT" |
| Rethrow | throw err inside catch, passing on an error you can't handle |
load() |
RangeError |
built-in error for a value outside the allowed range | No task number 5 |
TypeError |
built-in error for using a value the wrong way | setting a property on undefined |
SyntaxError (JSON) |
JSON.parse got text that isn't valid JSON |
{oops |
| Validation | checking input before using it | check(todos, n) |
Number.isInteger |
true only for whole numbers (false for NaN) |
Number.isInteger(2) |
| Index vs task number | 0-based position in the array vs 1-based number shown to people | task 2 = index 1 |
| Destructuring with rest | take the first items into names, the rest into an array | const [cmd, ...words] = ... |
| Spread | copy an array's or object's items into a new one | [...todos, task], { ...t, done: true } |
| Mutation | changing an existing array or object | todos[1].done = true |
| Pure function | same input → same output, changes nothing outside | markDone |
| Module | a file that exports values for other files | tasks.js |
module.exports / require |
share values from a module / bring them in | require("./tasks") |
| Separation of concerns | each part of the code has one job | logic, storage, I/O |
| Glue code | code that connects the parts | todo.js |
| Unit test | a test of one function on its own | tasks.test.js |
node --test |
run every test file in the folder | 3 passing |
| Exit code | number a program returns: 0 success, non-zero failure | process.exitCode = 1 |
| Relative path | a path looked up from the current folder | "todos.json" |
| Current working directory | the folder you ran the command from | process.cwd() |
| Silent data loss | data destroyed without any error | catching every error and saving [] |
Summary
- A CLI app is used by typing commands; we built
add,list,doneandremovefor Asha. - Data in memory is wiped when the program ends; persist it in a file. JSON with
JSON.stringify(todos, null, 2)andJSON.parseis the simplest format. fs.readFileSyncon the first run throwsENOENT: catch exactly that and start with[], and rethrow everything else.- Never trust user input:
todos[n - 1]with a badngivesTypeError: Cannot set properties of undefined. Check withNumber.isIntegerand the range, throw aRangeError, and return new arrays withmap/filterso the functions stay pure. - Three modules, three jobs:
tasks.js(pure logic, easy to test),store.js(the only file that touches the disk),todo.js(glue). - Test the pure functions with
node:test; read commands withprocess.argv.slice(2)(all strings); report failure withprocess.exitCode = 1. - A corrupt
todos.jsonshould fail loudly: a loud error is better than silent data loss.
Next episode: DSA in JavaScript 1: arrays, stacks and queues, the data structures every coding interview asks about.