AI Hints
Home›JavaScript Tutorial›Practice Projects 5
JavaScript · Lesson 129 of 138

Practice: A Notes CLI

A tool for the terminal.

⏱ 2 min read▶ Video at 2:34:40🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Let's build a tool you could really use in the terminal. A notes app that can add a note, list your notes, and clear them, saving everything in a JSON file. Commands like node notes add, buy milk.

Practice: A Notes CLI
From the video: Practice: A Notes CLI
  • A terminal tool
  • add, list, clear
  • Saved in a JSON file

Commands

Load reads the JSON file, or returns an empty array if it doesn't exist yet. Save writes it back. Run takes the command and its words. A switch picks what to do. Normally the arguments come from process dot argv, but to show a whole session, we call run several times ourselves. Run it.

notes.mjsjavascript
import { readFile, writeFile } from "node:fs/promises";
const FILE = "notes.json";
const load = async () => JSON.parse(await readFile(FILE, "utf8").catch(() => "[]"));
const save = (notes) => writeFile(FILE, JSON.stringify(notes, null, 2));

async function run(command, ...words) {
  const notes = await load();
  switch (command) {
    case "add": notes.push(words.join(" ")); await save(notes); console.log("Added."); break;
    case "list": notes.forEach((n, i) => console.log(`${i + 1}. ${n}`)); break;
    case "clear": await save([]); console.log("Cleared."); break;
    default: console.log("Usage: notes add|list|clear");
  }
}
// normally: await run(...process.argv.slice(2));
for (const args of [["add", "Buy", "milk"], ["add", "Call", "Sam"], ["list"], ["clear"], ["list"], ["help"]])
  await run(...args);
Output
Added.
Added.
1. Buy milk
2. Call Sam
Cleared.
Usage: notes add|list|clear

Making it a real command

Add a line at the very top, hash bang, slash user slash bin slash env node, and a bin field in package dot JSON. Then NPM link makes notes a real command on your computer. Many popular tools, like linters and build tools, are just Node scripts like this.

keyvalue
process.argv.slice(2)the user's words
JSON filesimple storage
switchpick the command
bin + npm linka real command

Summary

The notes tool used files, JSON, async functions, and a switch to make a useful command line app. Next, interview questions.

Key takeaways
  • fs/promises
  • process.argv
  • switch on the command
Next up: Interview Questions 1 — strings and arrays