Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 133 ยท Projects

Project: Command-Line To-Do App

Build a complete command-line to-do app in Node.js step by step - parse arguments with util.parseArgs, store tasks in a JSON file, add commands, handle errors and test it with node:test.

In this project you will build todo, a small command-line program you could really use: todo add "Buy milk" --due 2026-02-01, todo list, todo done 1, todo remove 1. It is a perfect first project because it touches the core skills of everyday Node.js: reading command-line arguments, reading and writing files, structuring code so it can be tested, reporting errors with proper exit codes, and writing automated tests.

We build it in four stages, and every stage is a complete program you can run right here. Along the way the design stays simple on purpose: a core of small functions that know nothing about the terminal, and a thin command layer on top. That separation is what makes the program easy to test. If you need a refresher first, see Command-Line Tools, fs.promises and The process Object.

In our editor a program cannot be started from a shell, so we call a run(argv) function with arrays like ['add', 'Buy milk']. On your computer, the same function receives process.argv.slice(2). Files you write here live only for one run, which is perfect for experiments.

Stage 1: parsing the command line

Typing node todo.mjs add "Buy milk" --due 2026-02-01 gives your program an array: process.argv is [nodePath, scriptPath, 'add', 'Buy milk', '--due', '2026-02-01'], and process.argv.slice(2) drops the first two. Splitting that array into commands, options and values by hand is tedious and full of edge cases (--due=2026-02-01, -a, --). Node has had util.parseArgs built in since v18.3, and it handles all of it.

You describe the options you accept: each has a type ('boolean' or 'string'), an optional one-letter short alias, and optionally multiple. Anything that is not an option comes back in positionals.

Node.js util.parseArgs on several command lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first call shows the whole result shape: values (a null-prototype object with the options that were given) and positionals (everything else, in order). The last call shows why strict mode is valuable: a typo like --colour is reported with the error code ERR_PARSE_ARGS_UNKNOWN_OPTION instead of being silently ignored. Our program will catch such errors and print a friendly message.

Stage 2: storing tasks in a JSON file

Next, a store. We keep all data in one JSON file shaped like { "nextId": 3, "items": [ ... ] }. A counter in the file gives every task a stable id that is never reused, even after removals (using the array index as an id would make todo done 2 mean something different after deleting task 1).

Three details separate a toy store from a dependable one:

  • A missing file is normal on the first run, so ENOENT returns an empty store, but any other error (permissions, corrupt JSON) is re-thrown.
  • Saving writes to a temporary file and then renames it over the real one. A rename is atomic on normal file systems, so a crash in the middle of writing can never leave a half-written todo.json.
  • The store functions take a file path as a parameter instead of hard-coding one, so tests can use a temporary file.
Node.js A JSON file store with atomic saves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that a corrupt file raises SyntaxError rather than silently resetting to an empty list, which would destroy the user's data on the next save. When in doubt, fail loudly.

Stage 3: the complete application

Now we combine everything into one module. The key design choice is a function run(argv, { file, out, err }) that returns an exit code instead of calling process.exit(). Exiting inside the logic makes testing painful, because the test process would die. The tiny wrapper at the very edge of the program is the only place that touches process. Output goes through out and err callbacks, so tests can capture it.

Exit codes follow the convention of real tools: 0 means success, 1 means a runtime problem (task not found), and 2 means the command line itself was wrong.

Node.js The finished to-do app, driven by a script of commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the transcript carefully. The third add is rejected with exit code 2 because --due tomorrow is a usage error, and nothing is saved, so the next id is not used up. done 99 fails with exit code 1 (the command was fine, the task does not exist). The unknown command and the unknown option are both exit code 2, and the final list -a shows the single task that is left, finished.

To turn this module into a real executable (read-only, for your machine), put a shebang on the very first line of the file and add this block at the end:

JavaScript
#!/usr/bin/env node
import { homedir } from 'node:os';
import { join } from 'node:path';

const file = process.env.TODO_FILE ?? join(homedir(), '.todo.json');
process.exitCode = await run(process.argv.slice(2), { file });

The first line (a shebang) lets Unix systems run the file directly after chmod +x todo.mjs, and a "bin" entry in package.json makes npm install -g put it on the PATH, as covered in Command-Line Tools. Setting process.exitCode instead of calling process.exit() lets pending writes finish before the process ends.

Do not call process.exit(code) right after writing a lot of output to a pipe: Node may exit before all of it is flushed. Set process.exitCode and return from your main function instead.

Stage 4: testing with node:test

Because run returns a code and takes its output as callbacks, tests need no tricks: call it with a temporary file, collect the output in an array, and assert. Node's built-in runner (node --test) finds files named *.test.mjs. See The Built-in Test Runner and Assertions for the details.

The next program writes a compact version of the app and its test file to disk, runs the tests through the runner's programmatic API, and prints each result. We use the API with our own few lines of reporting because the default reporter prints durations, which change on every run. On your machine you would simply run node --test.

Node.js Writing the app and its tests, then running them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each test creates its own temporary folder, so tests never share state and could run in any order. t.after() registers cleanup that runs even when an assertion fails. Notice the corrupt-file test: it checks the failure path, which is exactly the kind of case that is easy to forget and that causes data loss in real tools.

Stage 5: reading tasks from standard input

Unix tools compose through pipes: cat tasks.txt | todo import. A good CLI reads from process.stdin when asked. With readline you can read it line by line without loading everything. In our editor we preset the input; in a terminal the lines come from the pipe or the keyboard.

Node.js An import command that reads one task per line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the full app you would pass process.stdin into run as another option (like out), so tests can feed it a Readable.from([...]) stream.

Ideas to extend it

  • Add todo edit <id> <new text> and todo clear (remove all finished tasks).
  • Sort the list by due date, and mark overdue tasks. Pass "today" into the function instead of calling new Date() inside it, so tests stay deterministic.
  • Add colors with ANSI escape codes, but only when process.stdout.isTTY is true and NO_COLOR is not set.
  • Add --json output for scripting.
  • Replace the JSON file with SQLite and compare the code.
  • Guard against two copies of the program saving at the same time with a lock file.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which array does process.argv.slice(2) give you for node todo.mjs add "Buy milk"?

    The first two entries of process.argv are the Node executable and the script path. Slicing from index 2 leaves only the user's arguments.
  2. 2. What does util.parseArgs return in positionals?

    Options go to values. Everything else, such as the command word and its arguments, is in positionals (when allowPositionals is true).
  3. 3. Why does the store write to a temporary file and rename it?

    Readers see either the old complete file or the new complete file, never a partial one.
  4. 4. Why should run() return an exit code instead of calling process.exit()?

    Keeping process access at the edge makes the logic testable. The wrapper sets process.exitCode once.
  5. 5. A user mistypes a task id (todo done 99). Which result matches the project's conventions?

    Exit code 2 is reserved for bad command lines. A missing task is a runtime failure, so the app prints a short message and returns 1.

Summary

  • process.argv.slice(2) holds the user's arguments; util.parseArgs turns them into values and positionals and rejects unknown options.
  • Keep a clear split: a core that works on data, a command layer that returns exit codes, and a thin edge that touches process.
  • Store data in JSON with an incrementing id counter, treat ENOENT as an empty store, re-throw other errors, and save atomically with write-then-rename.
  • Pass file paths, output callbacks and input streams as parameters so tests can substitute them.
  • Test the happy paths and the failure paths with node:test, using a fresh temporary directory per test.
  • Set process.exitCode instead of calling process.exit() so output is flushed.

Next: Project: URL Shortener