Sub topic 4
Parsing Flags and Positional Arguments
This chapter assumes you know basic TypeScript, async and await, and how to run an npm script. It also assumes Node.js and TypeScript are installed. The goal is to turn raw command-line input into values your program can use safely.
A command-line argument is text supplied after the program name. For example:
wcl --lines notes.txtHere, --lines is a flag. A flag selects an option and usually does not need a value. notes.txt is a positional argument because its meaning comes from its position.
Reading arguments with `parseArgs`
Node.js includes parseArgs in the node:util module. It reads process.argv and matches arguments against an option definition.
process.argv contains more than the user’s input. The first item is the Node executable, and the second is the script path. The application’s arguments begin at index 2. parseArgs handles this detail when called without an explicit args value.
Create src/cli.ts:
#!/usr/bin/env node
import { parseArgs } from "node:util";
const { values, positionals } = parseArgs({
options: {
lines: {
type: "boolean",
short: "l",
},
help: {
type: "boolean",
short: "h",
},
},
allowPositionals: true,
});
console.log("lines only:", values.lines ?? false);
console.log("help:", values.help ?? false);
console.log("files:", positionals);The options object declares the accepted flags. Each option has a type. A boolean option is either present or absent. The short property adds a one-letter form.
For example, these commands produce equivalent option values:
node dist/cli.js --lines notes.txt
node dist/cli.js -l notes.txtThe result has two parts:
valuescontains named options such aslinesandhelp.positionalscontains arguments that were not identified as options.
The values are typed according to the option definitions. A boolean option is represented as boolean | undefined, because it is absent when the user does not provide it. The nullish coalescing operator gives it a default:
const linesOnly = values.lines ?? false;This preserves false while replacing only undefined.
Controlling positional arguments
Set allowPositionals to true when your command accepts file names or other unnamed values. Without it, an unexpected positional argument causes parsing to fail.
You can also stop option parsing with --. Everything after -- becomes positional input. This matters when a file name begins with a hyphen:
node dist/cli.js -- --notes.txtThe resulting positional list contains --notes.txt, rather than treating it as an option.
parseArgs rejects unknown flags by default. This is useful because misspelled options should fail early instead of silently changing the command’s behavior.
Validating the parsed boundary
Parsing and validation are separate steps. Parsing answers, “What did the user type?” Validation answers, “Is that acceptable for this command?”
For a file-counting tool, require exactly one file unless help was requested:
if (values.help) {
console.log("usage: wcl [-l] <file>");
process.exitCode = 0;
} else if (positionals.length !== 1) {
console.error("usage: wcl [-l] <file>");
process.exitCode = 2;
} else {
const file = positionals[0];
console.log(`ready to count ${file}`);
}Exit code 0 conventionally means success. A nonzero code tells scripts and shell users that the command failed. Code 2 commonly represents invalid command-line usage.
A simple processing flow looks like this:
Keeping parsing near the entry point gives the rest of the application a clearer contract. Later, you can convert the result into a typed command such as { kind: "count"; file: string; linesOnly: boolean }.
Exercise
What does allowPositionals: true change, and why would a file-counting command need it?
Show answer
It allows arguments that are not options to appear in the result’s positionals array. The command needs it to receive file names such as notes.txt.