Capstone A: commands from process.argv

A command line tool is a function from arguments to one of two things: a change to the file and a line of output, or a message and a status. The tracker has four commands, and each of them is a function over the array of tasks that returns a new array; the command line reads the file, calls one of them and saves the result.

The split is the same as in the earlier lessons of this part: src/commands.js holds the parsing and the four functions, and bin/tasks.js holds the file, the output and the status. The check program of the two previous lessons has done its work and is removed here, because the command line is now the program that runs.

process.argv and one action

Node.js fills process.argv with the path of the runtime, the path of the script and then the words the reader typed. The two first entries are the same on every run and are dropped with slice(2), which leaves the command and its arguments and nothing else.

The parser returns one object per call, with a type that names what to do. Every other shape (a set of functions, a switch in the command line) puts the knowledge of the arguments in two places; one object with a type keeps it in the parser, and the command line is a chain of questions about that object.

The folder already holds the model and the storage of the two previous lessons. The first command of this lesson adds the bin folder, and the second one removes the check program.

mkdir bin
rm check.js

The parser

add takes the rest of the words as the title, so a title with spaces needs no quotes. done and remove take one id and refuse anything that is not a positive integer, and list takes nothing. A word that is not a command, including no word at all, becomes a usage problem with a message of its own.

The four functions below the parser are the commands themselves. Each takes the array and returns a new one: add appends, complete maps the one task and remove filters. A task that is not in the list is a TaskError, which is the error the command line prints without a stack.

The file src/commands.js:

vi src/commands.js

const { Task, TaskError } = require('./task'); function parse(argv) { const [name, ...rest] = argv; if (name === 'add') { return { type: 'add', title: rest.join(' ') }; } if (name === 'list') { return { type: 'list' }; } if (name === 'done' || name === 'remove') { const id = Number(rest[0]); if (rest.length !== 1 || !Number.isInteger(id) || id < 1) { return { type: 'usage', message: name + ' takes one task id' }; } return { type: name, id }; } return { type: 'usage', message: 'unknown command: ' + String(name) }; } function find(tasks, id) { const task = tasks.find((entry) => entry.id === id); if (task === undefined) { throw new TaskError('no task with id ' + id); } return task; } function add(tasks, title) { const id = tasks.reduce((highest, task) => Math.max(highest, task.id), 0) + 1; return tasks.concat(new Task(id, title)); } function complete(tasks, id) { find(tasks, id); return tasks.map((task) => (task.id === id ? task.complete() : task)); } function remove(tasks, id) { find(tasks, id); return tasks.filter((task) => task.id !== id); } function render(tasks) { if (tasks.length === 0) { return 'no tasks'; } return tasks .map((task) => task.id + '. [' + (task.done ? 'x' : ' ') + '] ' + task.title) .join('\n'); } module.exports = { add, complete, parse, remove, render };

The next id is the highest id plus one and not the length of the array, because a list from which a task was removed has a hole and the length would hand out an id that is already in use. The reduce with a start of zero answers zero for an empty list, so the first task is number one.

The command line

The command line is short on purpose. It parses, prints a usage message and returns when the parse failed, loads the file, asks the action what to do, prints one line about the change and saves. The exit status is set with process.exitCode, so Node.js finishes writing the output before it exits, which the lesson on process explains.

The two kinds of failure are already separate. A wrong call is a usage error and returns 2 without touching the file; a task that is not there is a TaskError from the command and returns 1 from the catch around main. The statuses are the three of the lesson on bin and npx: 0, 1 and 2.

The file bin/tasks.js:

vi bin/tasks.js

#!/usr/bin/env node const { load, save } = require('../src/storage'); const { add, complete, parse, remove, render } = require('../src/commands'); const FILE = 'tasks.json'; async function main() { const action = parse(process.argv.slice(2)); if (action.type === 'usage') { console.error('error: ' + action.message); console.error('usage: add <title> | list | done <id> | remove <id>'); process.exitCode = 2; return; } const tasks = await load(FILE); if (action.type === 'list') { console.log(render(tasks)); return; } let next = tasks; if (action.type === 'add') { next = add(tasks, action.title); console.log('added the task ' + next[next.length - 1].id); } if (action.type === 'done') { next = complete(tasks, action.id); console.log('task ' + action.id + ' is done'); } if (action.type === 'remove') { next = remove(tasks, action.id); console.log('removed the task ' + action.id); } await save(FILE, next); } main().catch((error) => { console.error('error: ' + error.message); process.exitCode = 1; });

The shebang is not needed for node bin/tasks.js and is there for the day the file gets a link in node_modules/.bin. The file is in bin and requires ../src/storage, which is the relative path from the file and not from the folder the command was typed in.

A session

The folder starts without a task file, so the first two commands write it. The session adds two tasks, lists them, marks the first one as done, removes the second one and lists the list again. The last command asks for a task that does not exist, and the status after it is the one the shell reads.

node bin/tasks.js add write the tokenizer
node bin/tasks.js add test the tokenizer
node bin/tasks.js list
node bin/tasks.js done 1
node bin/tasks.js list
node bin/tasks.js remove 2
node bin/tasks.js list
node bin/tasks.js done 9
echo "the exit status: $?"

added the task 1
added the task 2
1. [ ] write the tokenizer
2. [ ] test the tokenizer
task 1 is done
1. [x] write the tokenizer
2. [ ] test the tokenizer
removed the task 2
1. [x] write the tokenizer
error: no task with id 9
the exit status: 1

Every command prints one line, and the two lists show the state between the commands. The box of a done task is an x, and the last line of the session is the message of the TaskError without a stack: the error was expected, so the program prints what it says and sets the status instead of letting Node.js print a trace.

The remove of task 2 left the list with one task whose id is 1. Add another task and it gets id 2, not 3, because the next id is counted from the tasks that are there. The exercise at the end of the previous chapter asked why; this is the run that shows it.

Exercises

  1. Add a task, remove it and add another one. Which id does the third task get, and which line of the parser decides it?
  2. Run node bin/tasks.js add with no title. Which message comes out, and what is the status?
  3. Add an undo command that marks a task as not done. Which two functions of the module does it need?
  4. Print the tasks in the order of their title instead of their id. Which method of the array does the change, and where does it go?
  5. Run the command from the folder above with node tasks/bin/tasks.js list. Which file does the tracker read, and why is that the right answer?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does process.argv.slice(2) hold?

    Answer

    The command and its arguments

    The first two entries are the runtime and the script, and the rest is what the reader typed.

  2. What does this program print? const argv = ["done", "3"]; const [name, ...rest] = argv; console.log(name, Number(rest[0]) + 1);

    Answer

    done 4

    The first word is the command and the rest holds the id as a string, which Number turns into a number.

  3. Why is the next id the highest id plus one rather than the length of the list?

    Answer

    A list with a removed task has a hole, and the length would repeat an id

    The highest id is the only value that no task in the list already uses.

  4. What does this program print? const tasks = [{ id: 1 }, { id: 2 }, { id: 3 }]; console.log(tasks.reduce((top, task) => Math.max(top, task.id), 0) + 1);

    Answer

    4

    The reducer keeps the highest id, three, and the next one is four.

  5. What does the command line print for a task that is not in the list?

    Answer

    The message of the error and the status 1

    The error is expected, so its message is the whole output and the status marks the failure.

  6. What does this program print? const tasks = [{ id: 1, done: true }, { id: 2, done: false }]; console.log(tasks.filter((task) => task.done).length);

    Answer

    1

    Only the first task has the flag set.

  7. Which status does a wrong command return in this project?

    Answer

    2

    The convention is 0 for success, 1 for a failure of the work and 2 for a wrong call.

  8. What does this program print? const tasks = [{ id: 1, done: false, title: "a" }]; const line = tasks.map((task) => task.id + ". [" + (task.done ? "x" : " ") + "] " + task.title); console.log(line[0]);

    Answer

    1. [ ] a

    A task that is not done gets a space between the brackets.

  9. Why does the command avoid process.exit?

    Answer

    Setting exitCode lets the pending output be written before the process ends

    The status is read when the process ends on its own, after the lines are flushed.

  10. What does this program print? const tasks = [{ id: 1 }, { id: 2 }]; const next = tasks.filter((task) => task.id !== 1); console.log(tasks.length, next.length);

    Answer

    2 1

    The filter returns a new array and leaves the first one as it was.

The programs and commands on this page were run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev