Node.js Mini Project: a CLI Todo App
Let's put the pieces together and build a real command-line tool: todo, a to-do list manager that saves its data in a JSON file. It uses process.argv for commands, node:util's parseArgs for options, node:fs for storage, and good error handling with exit codes.
When it's finished you'll use it like this:
$ node todo.js add "Buy milk"
Added #1: Buy milk
$ node todo.js add "Write tests" --priority high
Added #2: Write tests (high)
$ node todo.js done 1
Completed #1: Buy milk
$ node todo.js list
[ ] #2 Write tests (high)
[x] #1 Buy milk
1 of 2 doneAdded #1: Buy milk
Added #2: Write tests (high)
Completed #1: Buy milk
[ ] #2 Write tests (high)
[x] #1 Buy milk
1 of 2 done
Step 1: the plan
| Command | What it does |
|---|---|
add <text> [--priority high|normal|low] |
append a new todo |
list [--all | --open] |
show todos (--open hides finished ones) |
done <id> |
mark a todo as completed |
remove <id> |
delete a todo |
clear |
delete all completed todos |
The data file todos.json looks like this:
{
"nextId": 3,
"items": [
{ "id": 1, "text": "Buy milk", "done": true, "priority": "normal" },
{ "id": 2, "text": "Write tests", "done": false, "priority": "high" }
]
}Keeping nextId separately means ids are never reused after a todo is removed.
Step 2: loading and saving
Storage is two small functions. load returns an empty list when the file doesn't exist yet; save writes to a temporary file and then renames it, so a crash halfway through writing can never leave a half-written, corrupt todos.json (a rename is atomic on the same disk).
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 { nextId: 1, items: [] }; // first run
throw err;
}
}
function save(data) {
fs.writeFileSync(FILE + '.tmp', JSON.stringify(data, null, 2) + '\n');
fs.renameSync(FILE + '.tmp', FILE);
}
const data = load();
console.log('first load:', data);
data.items.push({ id: data.nextId++, text: 'Try the storage layer', done: false, priority: 'normal' });
save(data);
console.log('after save:', load().items.map((t) => t.text));
console.log(fs.readFileSync(FILE, 'utf8'));
fs.unlinkSync(FILE);first load: { nextId: 1, items: [] }
after save: [ 'Try the storage layer' ]
{
"nextId": 2,
"items": [
{
"id": 1,
"text": "Try the storage layer",
"done": false,
"priority": "normal"
}
]
}
Note: Only a missing file (
ENOENT) means "start empty". Any other error — like invalid JSON — is re-thrown, so we never silently overwrite a user's damaged data.
Step 3: the complete app
Here is the full program. To keep it runnable in one playground, the bottom of the file calls run() with several argument arrays — exactly what process.argv.slice(2) would contain if you typed each command in a terminal.
const fs = require('node:fs');
const { parseArgs } = require('node:util');
const FILE = 'todos.json';
const PRIORITIES = ['high', 'normal', 'low'];
// ---------- storage ----------
function load() {
try {
return JSON.parse(fs.readFileSync(FILE, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return { nextId: 1, items: [] };
throw err;
}
}
function save(data) {
fs.writeFileSync(FILE + '.tmp', JSON.stringify(data, null, 2));
fs.renameSync(FILE + '.tmp', FILE);
}
// ---------- helpers ----------
class UsageError extends Error {}
function format(t) {
const prio = t.priority === 'normal' ? '' : ` (${t.priority})`;
return `[${t.done ? 'x' : ' '}] #${t.id} ${t.text}${prio}`;
}
function findTodo(data, idText) {
const id = Number(idText);
if (!Number.isInteger(id)) throw new UsageError(`"${idText ?? ''}" is not a valid id`);
const todo = data.items.find((t) => t.id === id);
if (!todo) throw new UsageError(`No todo with id ${id}`);
return todo;
}
// ---------- commands ----------
const commands = {
add(data, args, opts) {
const text = args.join(' ').trim();
if (!text) throw new UsageError('Usage: todo add <text> [--priority high|normal|low]');
const priority = opts.priority ?? 'normal';
if (!PRIORITIES.includes(priority)) throw new UsageError(`Unknown priority "${priority}"`);
const todo = { id: data.nextId++, text, done: false, priority };
data.items.push(todo);
const prio = priority === 'normal' ? '' : ` (${priority})`;
console.log(`Added #${todo.id}: ${text}${prio}`);
return true; // true = data changed, save it
},
list(data, args, opts) {
const order = (t) => PRIORITIES.indexOf(t.priority);
const items = data.items
.filter((t) => !opts.open || !t.done)
.toSorted((a, b) => a.done - b.done || order(a) - order(b) || a.id - b.id);
if (items.length === 0) console.log('Nothing to do!');
for (const t of items) console.log(format(t));
const doneCount = data.items.filter((t) => t.done).length;
console.log(`${doneCount} of ${data.items.length} done`);
return false;
},
done(data, [id]) {
const todo = findTodo(data, id);
todo.done = true;
console.log(`Completed #${todo.id}: ${todo.text}`);
return true;
},
remove(data, [id]) {
const todo = findTodo(data, id);
data.items = data.items.filter((t) => t !== todo);
console.log(`Removed #${todo.id}: ${todo.text}`);
return true;
},
clear(data) {
const before = data.items.length;
data.items = data.items.filter((t) => !t.done);
console.log(`Cleared ${before - data.items.length} completed todo(s)`);
return true;
},
};
// ---------- entry point ----------
function run(argv) {
console.log(`$ todo ${argv.join(' ')}`);
try {
const { values: opts, positionals } = parseArgs({
args: argv,
allowPositionals: true,
options: {
priority: { type: 'string', short: 'p' },
open: { type: 'boolean' },
},
});
const [name, ...args] = positionals;
const command = commands[name];
if (!command) throw new UsageError(`Unknown command "${name ?? ''}". Try: ${Object.keys(commands).join(', ')}`);
const data = load();
if (command(data, args, opts)) save(data);
return 0; // exit code: success
} catch (err) {
if (err instanceof UsageError || err.code?.startsWith('ERR_PARSE_ARGS')) {
console.log(`error: ${err.message}`);
return 2; // exit code: bad usage
}
throw err; // real bugs should crash loudly
}
}
// In the real tool: process.exitCode = run(process.argv.slice(2));
const session = [
['add', 'Buy', 'milk'],
['add', 'Write tests', '--priority', 'high'],
['add', 'Water plants', '-p', 'low'],
['add', 'Call Mom'],
['done', '1'],
['list'],
['list', '--open'],
['remove', '3'],
['done', '42'],
['add', 'Party', '--priority', 'urgent'],
['fly'],
['clear'],
['list'],
];
for (const argv of session) {
const code = run(argv);
if (code !== 0) console.log(`(exit code ${code})`);
}
fs.unlinkSync(FILE); // tidy up the demo$ todo add Buy milk
Added #1: Buy milk
$ todo add Write tests --priority high
Added #2: Write tests (high)
$ todo add Water plants -p low
Added #3: Water plants (low)
$ todo add Call Mom
Added #4: Call Mom
$ todo done 1
Completed #1: Buy milk
$ todo list
[ ] #2 Write tests (high)
[ ] #4 Call Mom
[ ] #3 Water plants (low)
[x] #1 Buy milk
1 of 4 done
$ todo list --open
[ ] #2 Write tests (high)
[ ] #4 Call Mom
[ ] #3 Water plants (low)
1 of 4 done
$ todo remove 3
Removed #3: Water plants
$ todo done 42
error: No todo with id 42
(exit code 2)
$ todo add Party --priority urgent
error: Unknown priority "urgent"
(exit code 2)
$ todo fly
error: Unknown command "fly". Try: add, list, done, remove, clear
(exit code 2)
$ todo clear
Cleared 1 completed todo(s)
$ todo list
[ ] #2 Write tests (high)
[ ] #4 Call Mom
0 of 2 done
Some details worth noticing:
parseArgs(built intonode:util) handles--priority high,-p lowand boolean flags like--open, and rejects unknown options with anERR_PARSE_ARGS_…error.toSorted(ES2023) returns a sorted copy, so the stored order isn't changed by listing.- Exit codes matter for scripts:
0= success,2= wrong usage (a common convention). Settingprocess.exitCodeinstead of callingprocess.exit()lets pending output flush first. - Each command returns whether it changed the data, so
listnever rewrites the file.
Step 4: make it a real command
- Save the program as
todo.js, replace the demo session at the bottom withprocess.exitCode = run(process.argv.slice(2));and remove theconsole.log('$ todo …')line. - Add a shebang as the very first line:
#!/usr/bin/env node. - Create a
package.jsonwith abinentry and link it globally:
{
"name": "todo-cli",
"version": "1.0.0",
"bin": { "todo": "./todo.js" }
}$ npm link
added 1 package in 312ms
$ todo add "Learn Node.js" --priority high
Added #1: Learn Node.js (high)added 1 package in 312ms
Added #1: Learn Node.js (high)
Now todo works from any folder. To keep a single list no matter where you are, store the file in your home directory: path.join(os.homedir(), '.todos.json').
Ideas for extending it
- An
edit <id> <text>command. - Due dates with
--due 2026-12-31and anoverduecommand (compare withnew Date()). - Coloured output with
util.styleText('green', text)(Node 22+). - Tests with
node:testthat pointFILEto a temporary directory. - An
--jsonflag that prints raw JSON so other tools can consume it.
Test yourself
Why does save() write to todos.json.tmp and then rename it?
- Renaming is faster than writing
- So a crash mid-write never leaves a corrupt todos.json
- Because JSON files can't be overwritten
- To hide the file from the user
What does process.argv.slice(2) contain when you run node todo.js done 3?
['node', 'todo.js', 'done', '3']['done', '3']['done', 3]'done 3'
Why does load() only return an empty list for the ENOENT error code?
- Other errors can't happen
- To avoid silently overwriting a damaged file after other errors
- ENOENT means the JSON is invalid
- It's required by
JSON.parse