Skip to main content

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:

Text
node todo.js add "Buy bread"
node todo.js list
node todo.js done 1
node todo.js remove 1

Tasks 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:

Bash
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"
  }
}
JSON

The 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": true stops it being published to the npm registry by mistake.
  • "type": "module" tells Node.js that .js files here use import and export. It also allows await at the top level of a file, outside any function, which todo.js uses.
  • "test": "node --test" makes npm test run 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:

Bash
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 the node program and the path to todo.js. What is left is the words you typed.
  • const [command, ...rest] = ... is destructuring: command gets the first word, and ...rest collects every remaining word into an array called rest.

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:

Bash
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.json

How the parts work:

  • import { readFile, writeFile } from 'node:fs/promises' loads two file functions from Node.js. The node: prefix marks a module built into Node.js. These versions return promises, so you await them: the program waits for the disk without blocking everything else Node.js is doing.
  • loadTodos reads todos.json as UTF-8 text and turns it into an array with JSON.parse. The first time you run the app the file does not exist, and readFile throws an error whose code is 'ENOENT' (no such file). The catch treats that one case as an empty list and rethrows anything else, such as a permission problem, so real errors are not hidden.
  • saveTodos turns the array back into text. JSON.stringify(todos, null, 2) indents it by two spaces so you can read the file yourself.
  • fail prints a message to standard error with console.error and sets process.exitCode = 1. A non-zero exit code tells the shell, and any script running your app, that something went wrong. Setting exitCode rather than calling process.exit() lets Node.js finish any work still in progress before it stops.
  • printList uses two array methods. map makes a new array with one line of text per task, and its second argument, index, starts at 0, so index + 1 gives the numbers people expect. filter keeps only the finished tasks, and .length counts them.
  • const todos = await loadTodos() runs at the top level of the file. That is allowed because package.json says "type": "module".
  • switch (command) compares command with each case in turn. case 'list': and case undefined: share one block, so running node todo.js with no command also shows the list. break ends each case. default runs when nothing matched. The curly braces after case 'add': give text its 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:

Text
1. [ ] Buy bread
2. [ ] Call the landlord
3. [ ] Pay Adaeze ₦2,000
0 of 3 done

cat 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:

Bash
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 list

The new parts:

  • taskIndex checks the number before anything changes. Number(arg) converts the text '2' into the number 2. Text that is not a number, such as 'two', becomes NaN, and Number.isInteger rejects it, along with 1.5. The range check rejects 0, negative numbers and numbers past the end of the list. If the number is good, it returns number - 1, because people count from 1 and arrays count from 0. If not, it calls fail and returns -1, a value that cannot be a real position, and the caller stops with break.
  • done changes one property of one object in the array, then saves the whole array again.
  • remove uses filter to build a new array that keeps every task except the one at index. It saves the task first in removed so 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:

Text
1. [x] Buy bread
2. [ ] Pay Adaeze ₦2,000
1 of 2 done

The 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:

Bash
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 help

Check it worked

You see these four messages, each followed by exit status 1:

Text
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 await before readFile or saveTodos. 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 taskIndex does, and nowhere else.
  • Editing todos.json by hand and leaving a missing comma or quote. JSON.parse then throws a SyntaxError naming 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:

Bash
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 test

What the test file does:

  • test from node:test registers a test with a name and an async function. assert from node:assert/strict provides the checks; assert.equal fails if the two values differ.
  • promisify(execFile) gives you a run function that starts another program and returns a promise with its output. process.execPath is the full path to the node you are running, so the tests use the same Node.js version as you.
  • import.meta.dirname is the folder that holds the test file, so script points at todo.js wherever the project lives.
  • todo(folder, ...args) runs node todo.js with those arguments, using folder as the working directory. Because todo.js opens todos.json relative to the working directory, each test gets its own list.
  • mkdtemp creates a uniquely named empty folder under the system's temporary folder, and the finally block deletes it whether the test passes or fails.
  • In the second test, todo.js exits with code 1, so run rejects with an error. assert.rejects expects exactly that. The function you pass checks that the error's code (the exit code) is 1 and that its stderr contains the helpful message, then returns true to 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:

Bash
cd ~
rm -rf ~/todo-cli-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.