Sikau

Node.js · Day 6 · about 40 min

Project: A command-line todo app

Arguments, files and JSON together.

Your own terminal tool

Many developer tools are Node command-line programs (npm, vite, eslint). Build a small one: node todo.js add "Buy flour", node todo.js list, node todo.js done 1 — saving tasks to a JSON file.

Designing a command-line interface

Command-line tools are often the first useful programs people write in Node.

A good CLI feels predictable: a verb first, then its arguments — todo add "Buy flour", todo list, todo done 2. Each command does one thing, prints a short confirmation, and exits with code 0. Unknown commands or bad arguments print a helpful usage message and exit with a non-zero code so scripts can detect the failure.

const USAGE = `Usage:
  todo add <text>
  todo list
  todo done <id>`;

async function run([command, ...rest]) {
  switch (command) {
    case "add":  return add(rest.join(" "));
    case "list": return list();
    case "done": return done(Number(rest[0]));
    default:
      console.error(USAGE);
      process.exitCode = 1;
  }
}
await run(process.argv.slice(2));

Keeping run(args) separate from process.argv makes it easy to test: call run(["add", "Buy flour"]) directly instead of launching a new process.

The rest of this lesson

  • Data and edge casesexplain
  • Next idpredict
  • One commandorder
  • Situation → responsematch
  • Build the CLIchallenge
  • Badge quizquiz
  • Unit 1 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js