A command-line tool
A command-line tool is a program with three parts: a parser that turns the arguments into options, a report of what is wrong with them, and the work itself. The parser is a loop over process.argv, the report writes to standard error and sets the exit status, and the work runs only when the arguments made sense.
The lesson builds the three parts separately and then joins them into one small tool that appends notes to a file and lists them. The tool writes into a temporary folder so that a run leaves nothing behind, and it needs no package: a parser of this size is twenty lines, and the lessons on npm cover the libraries for the cases where it is not.
Parsing the arguments
The loop reads one argument at a time. A flag without a value sets a boolean, an option with a value consumes the next argument, an option written as --name=value is split on the first equals sign, and everything else is a positional argument such as a file name. The index is advanced by hand, which is the whole trick of the parser.
The program parses four arguments into an object with defaults and prints it as JSON, then prints the type of the count, because a value that came from the command line is a string until the parser converts it.
The file parse.mjs:
const parse = (argv) => {
const options = { count: 1, label: '', verbose: false, files: [] };
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument === '-v' || argument === '--verbose') {
options.verbose = true;
} else if (argument === '--count') {
index += 1;
options.count = Number(argv[index]);
} else if (argument.startsWith('--label=')) {
options.label = argument.slice('--label='.length);
} else {
options.files.push(argument);
}
}
return options;
};
const options = parse(process.argv.slice(2));
console.log('the options:', JSON.stringify(options));
console.log('the count is a number:', typeof options.count);
console.log('the files:', options.files.length);
node parse.mjs --count 3 --label=note -v notes.txt other.txt
the options: {"count":3,"label":"note","verbose":true,"files":["notes.txt","other.txt"]}
the count is a number: number
the files: 2
The two files became the positional list and the flag became a boolean, and the count is a number because the parser called Number on the string. A parser that trusts the value gives NaN for a word, which is why the next section checks every option before the work starts.
Problems and the exit status
A tool reports a bad command line on standard error, prints every problem it found and exits with a non-zero status. The collecting order matters: a user who wrote three wrong options should see three lines and not the first one only. Nothing is written to standard output in that case, which keeps the output of a successful run free of messages.
The program checks each argument and collects the problems, then prints them and sets process.exitCode. The command sends standard error into the same stream as standard output and prints the status the shell read.
The file validate.mjs:
const argv = process.argv.slice(2);
const problems = [];
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument === '--count') {
const value = argv[index + 1];
if (value === undefined || Number.isNaN(Number(value))) {
problems.push('--count needs a number');
}
index += 1;
} else if (argument !== '--quiet') {
problems.push('unknown option: ' + argument);
}
}
if (problems.length > 0) {
for (const problem of problems) {
console.error('error:', problem);
}
process.exitCode = 1;
} else {
console.log('the arguments are fine');
}
node validate.mjs --count 3 --size 2>&1
echo "exit code: $?"
error: unknown option: --size
exit code: 1
The count was fine and the unknown option was not, so the program printed one line and left with one. The redirection in the command is what puts the message in the block above; a reader who runs the tool without it sees the message on the terminal all the same, because both streams go there by default.
Usage text
A tool that refuses arguments should say what it accepts. The usage text names the program, lists the options with their arguments aligned in a column, and prints to standard output for --help and to standard error when the arguments were simply wrong. The text lives in one array and is joined once, so the lines stay aligned in the source as well.
The program prints the usage text for --help, and prints the same text with an error and a status of one when it is started with no arguments at all.
The file help.mjs:
const usage = [
'usage: note [options] <file>',
' --add TEXT append one note',
' --list print the notes',
' --help show this text',
].join('\n');
const argv = process.argv.slice(2);
if (argv.includes('--help')) {
console.log(usage);
} else if (argv.length === 0) {
console.error('error: no arguments given');
console.log(usage);
process.exitCode = 1;
} else {
console.log('the tool would run with', argv.length, 'arguments');
}
node help.mjs --help
usage: note [options] <file>
--add TEXT append one note
--list print the notes
--help show this text
The three options are the shape of the tool in the last section: --add takes a text, --list prints what is there, and --help explains both. A program that prints its usage on a wrong command line is easier to use than one that leaves the reader with a stack trace.
The whole tool
The tool walks the arguments in order and performs each request as it meets it, so --add first --add second --list appends two notes and then lists them. A missing text after --add and an unknown option both throw, one catch turns the message into a line on standard error and a status of one, and the finally block removes the temporary folder on both paths.
The folder is made with mkdtemp at the start and removed at the end, so the notes a reader adds exist only for that run. A real tool would take the file as an argument and skip the removal, which is the exercise at the end of the lesson.
The file tool.mjs:
import { appendFile, mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'note-'));
const file = join(dir, 'notes.txt');
const argv = process.argv.slice(2);
try {
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument === '--add') {
const text = argv[index + 1];
if (text === undefined) {
throw new Error('--add needs a text');
}
await appendFile(file, text + '\n');
index += 1;
} else if (argument === '--list') {
const text = await readFile(file, 'utf8').catch(() => '');
const notes = text.trimEnd().split('\n').filter((line) => line !== '');
notes.forEach((note, number) => {
console.log(number + 1, note);
});
console.log('the number of notes:', notes.length);
} else {
throw new Error('unknown option: ' + argument);
}
}
} catch (error) {
console.error('error:', error.message);
process.exitCode = 1;
} finally {
await rm(dir, { force: true, recursive: true });
}
node tool.mjs --add first --add second --list
1 first
2 second
the number of notes: 2
The tool numbered the two notes and reported how many there are, and the exit status was zero because the arguments were fine. Run it with --add alone and the same program prints --add needs a text and leaves with one, which is the difference between a tool that accepts anything and one a script can call.
Exercises
- Add a --quiet flag that suppresses the line with the number of notes.
- Accept -c as a short form of --count. Which branch of the parser changes?
- Print the usage text when an unknown option is found, and check the exit status of that run.
- Make --list print the number of bytes of the file as well as the notes. Which call gives that number?
- Take the notes file from a positional argument instead of the temporary folder, and remove the finally block. What should the usage text say about the folder?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where does a script read its own arguments?
Answer
process.argv.slice(2)
The first two entries are the runtime and the script itself.
-
What does this program print?
const argv = ["--count", "3", "--label=note", "-v"]; const options = { count: 1, label: "", verbose: false }; for (let index = 0; index < argv.length; index += 1) { const argument = argv[index]; if (argument === "-v") { options.verbose = true; } else if (argument === "--count") { index += 1; options.count = Number(argv[index]); } else if (argument.startsWith("--label=")) { options.label = argument.slice("--label=".length); } } console.log(JSON.stringify(options));Answer
{"count":3,"label":"note","verbose":true}
The parser converted the count, split the label on the equals sign and set the flag.
-
What should a tool do with an unknown option?
Answer
Print a message and exit with a non-zero status
A wrong command line is a failure of the caller, and the status tells a script so.
-
What does this program print?
const argv = ["--count"]; console.log(argv[1] === undefined);Answer
true
The option is the last argument, so the value that should follow it is missing.
-
Which stream should the errors of a command-line tool use?
Answer
Standard error
A program that parses the output of the tool must not receive the messages.
-
What does this program print?
const code = Number("3"); console.log(typeof code);Answer
number
Number converts the string, and the parser has to call it because argv holds strings.
-
What does --help usually do?
Answer
Print the usage text and exit with zero
The user asked for something the tool can do, so the status is a success.
-
What does this program print?
const words = ["--add", "first"]; console.log(words.slice(1).join(" "));Answer
first
slice(1) drops the option name and leaves the value it takes.
-
Why does the tool set process.exitCode instead of calling process.exit?
Answer
Output that is still being written is not lost
The program ends when the event loop is empty, so the last write reaches the terminal.
-
What belongs on standard output of a tool?
Answer
The result of its work and nothing else
The output is data for the next program in a pipeline, so messages go to standard error.
The code on this page was 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