Programming fundamentals · Beginner · 20 min
Build a to-do list command-line app in Node.js
By Padding · Updated 18 Nov 2026
Node.js 26.13.1 LTS · npm 11.20 · node:26 image
You will build todo.js, a Node.js command-line app with add, list, done and remove commands that keeps your tasks in a JSON file, gives clear messages for mistakes and is covered by two passing tests.
On this page
A command-line app is a program you run by typing its name and some words after it. Many of the tools developers use every day work this way: git, npm, node itself. Building one is a good first project because it uses the core parts of programming together: reading input, making decisions, storing data in a list, saving it to a file and reporting errors, with nothing else in the way.
In this tutorial you build todo.js, a to-do list you use like this:
node todo.js add "Buy bread"
node todo.js list
node todo.js done 1
node todo.js remove 1Tasks are kept in a file called todos.json, so they are still there the next time you run the app. You finish with two automated tests that prove the app works. The project needs no npm packages, so there is nothing to download beyond Node.js itself, which helps on prepaid data. It also runs on a modest laptop, and on an Android phone with Node.js installed through Termux.
Commands are shown for a Linux or macOS shell. On Windows, PowerShell runs the node and npm commands the same way.
Step 1 · Set up the project folder
Check your Node.js version, then make a folder and add a package.json file to it:
node --version
mkdir -p ~/todo-cli-demo
cd ~/todo-cli-demo
cat > package.json <<'JSON'
{
"name": "todo-cli-demo",
"private": true,
"type": "module",
"scripts": {
"test": "node --test"
}
}
JSONThe cat > package.json <<'JSON' line writes everything up to the closing JSON line into the file. You can also create the file in your editor and paste the part between those lines.
What each part of package.json does:
"name"labels the project."private": truestops it being published to the npm registry by mistake."type": "module"tells Node.js that.jsfiles here useimportandexport. It also allowsawaitat the top level of a file, outside any function, whichtodo.jsuses."test": "node --test"makesnpm testrun Node.js's built-in test runner, which you use in the last step.
Check it worked
node --version prints v26 followed by a minor and patch number, such as v26.13.1. If it prints a lower major version, install Node.js 26 first. Run cat package.json and you see the file as written above.
Step 2 · Read the command from process.argv
When you run node todo.js add Buy bread, Node.js puts every word of that command into an array called process.argv. Write a first, small todo.js to see what is in it:
cat > todo.js <<'JS'
console.log(process.argv);
const [command, ...rest] = process.argv.slice(2);
console.log('command:', command);
console.log('rest:', rest);
JS
node todo.js add Buy bread
node todo.js add "Buy bread"Line by line:
console.log(process.argv)prints the whole array.process.argv.slice(2)returns a new array without the first two items, which are the path to thenodeprogram and the path totodo.js. What is left is the words you typed.const [command, ...rest] = ...is destructuring:commandgets the first word, and...restcollects every remaining word into an array calledrest.
Check it worked
The first line of each run is an array that starts with two long paths, one ending in node and one ending in todo.js. Then the first run prints command: add and rest: [ 'Buy', 'bread' ], and the second prints command: add and rest: [ 'Buy bread' ]. The quotes made the shell pass Buy bread as one word. The app will join the words back together, so both forms work.
Step 3 · Add and list tasks saved in todos.json
Now replace todo.js with a version that stores tasks. Each task is an object such as { "text": "Buy bread", "done": false }, and the whole list is an array of those objects, saved as JSON:
cat > todo.js <<'JS'
import { readFile, writeFile } from 'node:fs/promises';
const FILE = 'todos.json';
async function loadTodos() {
try {
const text = await readFile(FILE, 'utf8');
return JSON.parse(text);
} catch (error) {
if (error.code === 'ENOENT') {
return [];
}
throw error;
}
}
async function saveTodos(todos) {
await writeFile(FILE, JSON.stringify(todos, null, 2) + '\n', 'utf8');
}
function fail(message) {
console.error(message);
process.exitCode = 1;
}
function printList(todos) {
if (todos.length === 0) {
console.log('No tasks yet. Add one with: node todo.js add "Buy bread"');
return;
}
const lines = todos.map((todo, index) => {
const mark = todo.done ? 'x' : ' ';
return `${index + 1}. [${mark}] ${todo.text}`;
});
console.log(lines.join('\n'));
const doneCount = todos.filter((todo) => todo.done).length;
console.log(`${doneCount} of ${todos.length} done`);
}
const [command, ...rest] = process.argv.slice(2);
const todos = await loadTodos();
switch (command) {
case 'add': {
const text = rest.join(' ').trim();
if (text === '') {
fail('Write the task after add, for example: node todo.js add "Buy bread"');
break;
}
todos.push({ text, done: false });
await saveTodos(todos);
console.log(`Added task ${todos.length}: ${text}`);
break;
}
case 'list':
case undefined:
printList(todos);
break;
default:
fail(`Unknown command "${command}". Try: add, list`);
}
JS
node todo.js list
node todo.js add "Buy bread"
node todo.js add Call the landlord
node todo.js add "Pay Adaeze ₦2,000"
node todo.js list
cat todos.jsonHow the parts work:
import { readFile, writeFile } from 'node:fs/promises'loads two file functions from Node.js. Thenode:prefix marks a module built into Node.js. These versions return promises, so youawaitthem: the program waits for the disk without blocking everything else Node.js is doing.loadTodosreadstodos.jsonas UTF-8 text and turns it into an array withJSON.parse. The first time you run the app the file does not exist, andreadFilethrows an error whosecodeis'ENOENT'(no such file). Thecatchtreats that one case as an empty list and rethrows anything else, such as a permission problem, so real errors are not hidden.saveTodosturns the array back into text.JSON.stringify(todos, null, 2)indents it by two spaces so you can read the file yourself.failprints a message to standard error withconsole.errorand setsprocess.exitCode = 1. A non-zero exit code tells the shell, and any script running your app, that something went wrong. SettingexitCoderather than callingprocess.exit()lets Node.js finish any work still in progress before it stops.printListuses two array methods.mapmakes a new array with one line of text per task, and its second argument,index, starts at 0, soindex + 1gives the numbers people expect.filterkeeps only the finished tasks, and.lengthcounts them.const todos = await loadTodos()runs at the top level of the file. That is allowed becausepackage.jsonsays"type": "module".switch (command)comparescommandwith eachcasein turn.case 'list':andcase undefined:share one block, so runningnode todo.jswith no command also shows the list.breakends each case.defaultruns when nothing matched. The curly braces aftercase 'add':givetextits own scope inside that case.
Files are read and written as UTF-8, so task text in any language or script, and symbols such as ₦, is stored exactly as you typed it.
Check it worked
The first list prints No tasks yet. Add one with: node todo.js add "Buy bread". Each add prints a line such as Added task 2: Call the landlord. The second list prints:
1. [ ] Buy bread
2. [ ] Call the landlord
3. [ ] Pay Adaeze ₦2,000
0 of 3 donecat todos.json shows the same three tasks as an indented JSON array, each with "done": false.
Step 4 · Mark tasks done and remove them
Replace todo.js with the full version. It adds done, remove and help, and a taskIndex function that turns the number the user typed into a position in the array, or explains why it cannot:
cat > todo.js <<'JS'
import { readFile, writeFile } from 'node:fs/promises';
const FILE = 'todos.json';
async function loadTodos() {
try {
const text = await readFile(FILE, 'utf8');
return JSON.parse(text);
} catch (error) {
if (error.code === 'ENOENT') {
return [];
}
throw error;
}
}
async function saveTodos(todos) {
await writeFile(FILE, JSON.stringify(todos, null, 2) + '\n', 'utf8');
}
function fail(message) {
console.error(message);
process.exitCode = 1;
}
function printList(todos) {
if (todos.length === 0) {
console.log('No tasks yet. Add one with: node todo.js add "Buy bread"');
return;
}
const lines = todos.map((todo, index) => {
const mark = todo.done ? 'x' : ' ';
return `${index + 1}. [${mark}] ${todo.text}`;
});
console.log(lines.join('\n'));
const doneCount = todos.filter((todo) => todo.done).length;
console.log(`${doneCount} of ${todos.length} done`);
}
function printHelp() {
console.log(`Usage:
node todo.js add <task> add a task
node todo.js list show all tasks
node todo.js done <number> mark a task as done
node todo.js remove <number> delete a task
node todo.js help show this message`);
}
function taskIndex(arg, todos) {
if (arg === undefined) {
fail('Give a task number, for example: node todo.js done 1');
return -1;
}
const number = Number(arg);
if (!Number.isInteger(number) || number < 1 || number > todos.length) {
fail(`No task number "${arg}". Run node todo.js list to see the numbers.`);
return -1;
}
return number - 1;
}
const [command, ...rest] = process.argv.slice(2);
const todos = await loadTodos();
switch (command) {
case 'add': {
const text = rest.join(' ').trim();
if (text === '') {
fail('Write the task after add, for example: node todo.js add "Buy bread"');
break;
}
todos.push({ text, done: false });
await saveTodos(todos);
console.log(`Added task ${todos.length}: ${text}`);
break;
}
case 'list':
case undefined:
printList(todos);
break;
case 'done': {
const index = taskIndex(rest[0], todos);
if (index === -1) {
break;
}
if (todos[index].done) {
console.log(`Task ${index + 1} is already done.`);
break;
}
todos[index].done = true;
await saveTodos(todos);
console.log(`Done: ${todos[index].text}`);
break;
}
case 'remove': {
const index = taskIndex(rest[0], todos);
if (index === -1) {
break;
}
const removed = todos[index];
const remaining = todos.filter((todo, i) => i !== index);
await saveTodos(remaining);
console.log(`Removed: ${removed.text}`);
break;
}
case 'help':
printHelp();
break;
default:
fail(`Unknown command "${command}". Run node todo.js help to see the commands.`);
}
JS
node todo.js done 1
node todo.js remove 2
node todo.js listThe new parts:
taskIndexchecks the number before anything changes.Number(arg)converts the text'2'into the number2. Text that is not a number, such as'two', becomesNaN, andNumber.isIntegerrejects it, along with1.5. The range check rejects0, negative numbers and numbers past the end of the list. If the number is good, it returnsnumber - 1, because people count from 1 and arrays count from 0. If not, it callsfailand returns-1, a value that cannot be a real position, and the caller stops withbreak.donechanges one property of one object in the array, then saves the whole array again.removeusesfilterto build a new array that keeps every task except the one atindex. It saves the task first inremovedso it can tell you what it deleted.
The original todos array is never changed by remove; the new array is what gets saved. Building a new array instead of editing the old one in place is a common habit in JavaScript, because it makes code easier to follow.
Check it worked
done 1 prints Done: Buy bread and remove 2 prints Removed: Call the landlord. The final list prints:
1. [x] Buy bread
2. [ ] Pay Adaeze ₦2,000
1 of 2 doneThe numbers moved up after the removal: the task that was 3 is now 2. Numbers are positions in the list, not fixed IDs, so run list before done or remove to see the current ones.
Step 5 · Try the error messages
A good command-line app tells you what went wrong and what to do next. Try each mistake on purpose. The || echo "exit status $?" part runs only when the command before it fails, and shows the exit code:
node todo.js done 7 || echo "exit status $?"
node todo.js done two || echo "exit status $?"
node todo.js remove || echo "exit status $?"
node todo.js finish 1 || echo "exit status $?"
node todo.js helpCheck it worked
You see these four messages, each followed by exit status 1:
No task number "7". Run node todo.js list to see the numbers.
No task number "two". Run node todo.js list to see the numbers.
Give a task number, for example: node todo.js done 1
Unknown command "finish". Run node todo.js help to see the commands.Then help prints the usage list. Run node todo.js list once more: nothing changed, because every check happens before the app saves.
Three mistakes beginners often make with apps like this:
- Forgetting
awaitbeforereadFileorsaveTodos. Without it you get a promise object instead of the file contents, or the app moves on before the file is written. - Mixing up positions and numbers. Arrays start at 0; the list the user sees starts at 1. Convert in one place, as
taskIndexdoes, and nowhere else. - Editing
todos.jsonby hand and leaving a missing comma or quote.JSON.parsethen throws aSyntaxErrornaming the position. Fix the file, or delete it to start again with an empty list.
Step 6 · Test the app with node:test
Typing commands by hand works once. Tests repeat the checks for you every time you change the code. Write todo.test.js with two tests. Each one runs the real todo.js in a new, empty temporary folder, so it starts with no todos.json and never touches your own tasks:
cat > todo.test.js <<'JS'
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const run = promisify(execFile);
const script = join(import.meta.dirname, 'todo.js');
async function todo(folder, ...args) {
const { stdout } = await run(process.execPath, [script, ...args], { cwd: folder });
return stdout;
}
test('add then list shows a numbered task', async () => {
const folder = await mkdtemp(join(tmpdir(), 'todo-test-'));
try {
await todo(folder, 'add', 'Buy bread');
const output = await todo(folder, 'list');
assert.equal(output, '1. [ ] Buy bread\n0 of 1 done\n');
} finally {
await rm(folder, { recursive: true, force: true });
}
});
test('done with a bad number fails with a helpful message', async () => {
const folder = await mkdtemp(join(tmpdir(), 'todo-test-'));
try {
await todo(folder, 'add', 'Buy bread');
await assert.rejects(todo(folder, 'done', '5'), (error) => {
assert.equal(error.code, 1);
assert.match(error.stderr, /No task number "5"/);
return true;
});
} finally {
await rm(folder, { recursive: true, force: true });
}
});
JS
npm testWhat the test file does:
testfromnode:testregisters a test with a name and an async function.assertfromnode:assert/strictprovides the checks;assert.equalfails if the two values differ.promisify(execFile)gives you arunfunction that starts another program and returns a promise with its output.process.execPathis the full path to thenodeyou are running, so the tests use the same Node.js version as you.import.meta.dirnameis the folder that holds the test file, soscriptpoints attodo.jswherever the project lives.todo(folder, ...args)runsnode todo.jswith those arguments, usingfolderas the working directory. Becausetodo.jsopenstodos.jsonrelative to the working directory, each test gets its own list.mkdtempcreates a uniquely named empty folder under the system's temporary folder, and thefinallyblock deletes it whether the test passes or fails.- In the second test,
todo.jsexits with code 1, sorunrejects with an error.assert.rejectsexpects exactly that. The function you pass checks that the error'scode(the exit code) is 1 and that itsstderrcontains the helpful message, then returnstrueto accept the error.
Check it worked
npm test finds todo.test.js by its .test.js ending and runs it. The output lists both test names with a tick, and the summary includes pass 2 and fail 0. To see a failure, change '0 of 1 done' in the first test to '1 of 1 done', run npm test again and read the expected and actual values it prints, then change it back.
When you have finished, delete the demo folder:
cd ~
rm -rf ~/todo-cli-demoNext steps
- Go further with the array methods
todo.jsuses: work with arrays in JavaScript with map, filter and reduce. - Move the file functions into their own module and import them: use JavaScript modules with import and export.
- Understand what
awaitis waiting for: wait for slow work with promises and async/await. - Write more tests, and learn to read a failure: write your first JavaScript tests with the Node.js test runner.
Part of these paths
Related tutorials
- Work with arrays in JavaScript: map, filter and reduceYou will turn a list of shop products into prices with tax, in-stock lists, yes-or-no answers, totals and a sorted stock report, using map, filter, find, some, every, reduce and toSorted in Node.js 26.
- Use JavaScript modules with import and exportYou will split a Node.js bill-splitting script into three ES modules with named and default exports, load built-ins and code on demand, recognise CommonJS and its errors, and run the same modules in a browser.
- Wait for slow work in JavaScript with promises and async/awaitYou will see why JavaScript code seems to run out of order, wrap a timer in a promise, rewrite it with async/await and try/catch, time three requests one after another against all at once, and finish with a script that loads files in parallel and reports any that failed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials