Sub topic 4
Parsing flags and positional arguments
This chapter shows how to turn the raw words a user types after wcl into structured values. It uses the built-in node:util function parseArgs. It assumes you have a project that compiles TypeScript to Node.js ESM and an entry file with a shebang line. It also assumes you know what process.argv is, at least roughly. The next chapters cover validating what comes out of the parser and turning it into a typed command.
What the shell hands your program
When a user runs wcl -l notes.txt, the shell splits the line into words and starts Node with those words as an array. Node exposes that array as process.argv. The first two entries are always the path of the Node executable and the path of the script being run. Your own arguments start at index 2.
console.log(process.argv);
// ["/usr/bin/node", "/home/me/wcl/dist/cli.js", "-l", "notes.txt"]You could loop over this array by hand, but that grows messy quickly. You would have to handle -l, --lines, grouped short flags like -lw, values attached with =, and the -- separator. parseArgs handles all of these with one declarative description of your options.
The words fall into three groups:
- Flags are options that are either present or absent, such as
-lor--help. InparseArgsthey have typeboolean. - Options with values carry a string, such as
--encoding utf8. InparseArgsthey have typestring. - Positional arguments are everything else, such as the file name
notes.txt.
The basic call
parseArgs takes a configuration object and returns { values, positionals }. By default it reads process.argv and skips the first two entries for you.
#!/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(values.lines ?? false, positionals);Each key in options is the long name, used as --lines. The optional short property is a single character used as -l. The type is required and must be "boolean" or "string".
Two details matter here:
values.linesisboolean | undefined. If the user does not pass the flag, the key is absent fromvalues, so the code uses?? false. TypeScript infers this from youroptionsobject, so a typo likevalues.linefails at compile time.allowPositionals: trueis required to accept a file name. Without it, any positional argument makesparseArgsthrow.
Build and run the example to see it work:
npm run build
node dist/cli.js -l notes.txt
# true [ 'notes.txt' ]
node dist/cli.js notes.txt
# false [ 'notes.txt' ]Accepted syntax
The same configuration accepts many spellings of the same input. The table lists the forms you can rely on.
| User types | Meaning |
|---|---|
| `--lines` | Long boolean flag |
| `-l` | Short boolean flag |
| `-lw` | Two short boolean flags grouped together |
| `--encoding utf8` | Long string option, value in the next word |
| `--encoding=utf8` | Long string option, value attached with `=` |
| `-e utf8` | Short string option, value in the next word |
| `-eutf8` | Short string option, value attached directly |
| `--` | End of options. Every later word is positional |
The -- separator matters when a file name starts with a dash. After wcl -- -weird.txt, the parser treats -weird.txt as a positional argument instead of an unknown flag. This convention is shared by most Unix tools, so users expect it to work.
A boolean flag never takes a value. --lines=true is an error, not a way to say "yes". A string option always requires a value, so --encoding with nothing after it is also an error.
Strict mode and its errors
parseArgs has a strict setting that defaults to true. In strict mode it throws a TypeError for input that does not match your configuration:
- An option you did not declare, such as
--colour. - A string option with no value.
- A boolean option given a value.
- A positional argument when
allowPositionalsis not set.
Each error carries a code property starting with ERR_PARSE_ARGS_. For example, an unknown option gives ERR_PARSE_ARGS_UNKNOWN_OPTION. If you leave the error uncaught, the user sees a stack trace, which is a poor experience for a typo. Catch it, print one clear line to standard error, and return a non-zero exit code.
#!/usr/bin/env node
import { parseArgs } from "node:util";
function parse(argv: string[]) {
try {
return parseArgs({
args: argv,
options: {
lines: { type: "boolean", short: "l" },
help: { type: "boolean", short: "h" },
},
allowPositionals: true,
});
} catch (err) {
if (
err instanceof TypeError &&
"code" in err &&
typeof err.code === "string" &&
err.code.startsWith("ERR_PARSE_ARGS_")
) {
console.error(`wcl: ${err.message}`);
return undefined;
}
throw err;
}
}
const parsed = parse(process.argv.slice(2));
if (parsed === undefined) {
process.exitCode = 2;
} else {
console.log(parsed.values.lines ?? false, parsed.positionals);
}The catch block only handles parser errors. Anything else is rethrown, because swallowing an unrelated bug would hide it.
node dist/cli.js --colour notes.txt
# wcl: Unknown option '--colour'. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- "--colour"'
echo $?
# 2The exact message text comes from Node and can change between versions. Check the code property when you need to react to a specific failure, and treat the message as text for people.
The flow from argv to values
The diagram shows what happens between the shell and your code. The parser either returns a structured result or throws, and your wrapper decides what the user sees.
Passing your own args
The args option replaces process.argv. When you set it, parseArgs does not skip anything, so the array must contain only the user's words. The example above uses process.argv.slice(2) for this reason.
Passing args explicitly is more than a convenience. A function parse(argv: string[]) takes its input as a parameter, so you can call it from a test with any array and never touch the real process. The main(argv) function in the final program uses the same pattern.
String options, defaults, and repeated options
String options and repeated options work the same way as flags. The following program runs as written, because it supplies its own args.
import { parseArgs } from "node:util";
const { values, positionals } = parseArgs({
args: ["-l", "--exclude", "a.txt", "--exclude=b.txt", "--", "-weird.txt"],
options: {
lines: { type: "boolean", short: "l" },
exclude: { type: "string", multiple: true },
encoding: { type: "string", default: "utf8" },
},
allowPositionals: true,
});
console.log(values);
console.log(positionals);The output is:
[Object: null prototype] { lines: true, exclude: [ 'a.txt', 'b.txt' ], encoding: 'utf8' }
[ '-weird.txt' ]Four behaviors show up here:
multiple: truecollects every occurrence into an array. The type becomesstring[] | undefined. Withoutmultiple, a repeated option keeps only the last value.defaultfills in a value when the user omits the option. TypeScript's inferred type for that key then no longer includesundefined.valuesis an object with anullprototype, which is why Node prints[Object: null prototype]. Reading properties works normally, butvalues.hasOwnProperty(...)does not exist. Use"lines" in valuesorObject.hasOwn(values, "lines")instead.-weird.txtended up inpositionalsbecause it came after--.
Gotchas
- Negative numbers and values starting with a dash.
--offset -1is ambiguous, because-1looks like a short option. Write--offset=-1instead so the value is attached unambiguously. - Short names are one character.
short: "lines"is not valid. Pick a single character and keep it unique across options. - Absent is not false. A flag the user did not pass is
undefined, notfalse. If a later step compares with=== false, it will behave wrongly. Normalize with?? falseonce, close to the parser. - No automatic help text.
parseArgsdoes not generate--helpoutput or check that required arguments are present. It only parses. You decide thathelptriggers a usage message, and you check the number of positionals yourself. - No type conversion. A string option is always a string. If you add
--maxand expect a number, you convert and check it yourself. - Node version.
parseArgsexists in Node 18.3 and later, and 16.17 and later. Some extras, such asallowNegative, appeared in newer releases. Check the Node documentation if you rely on an option beyond the ones shown here.
What to do with the result
At this point the parser has confirmed the shape of the input. It has not confirmed that the input makes sense. positionals may be empty, or it may hold three file names when your tool takes one. The help flag may be set together with other arguments. The next chapter handles those checks at the boundary, and the one after turns the checked result into a discriminated union so the rest of the code never reads raw values again.
Exercise
A user runs wcl -l -- -notes.txt. Using the parseArgs configuration with a lines boolean (short l), a help boolean (short h) and allowPositionals: true, what are values.lines and positionals? Then explain what changes if the user omits the --.
Show answer
values.lines is true and positionals is ["-notes.txt"]. The -- ends option parsing, so -notes.txt is treated as a positional argument even though it starts with a dash. Without --, strict mode would read -notes.txt as a group of short options (-n, -o, and so on). The first undeclared one would make parseArgs throw a TypeError with code ERR_PARSE_ARGS_UNKNOWN_OPTION.
Exercise
Add a --max-lines string option to the configuration, and say what values["max-lines"] is for the input wcl --max-lines 10 notes.txt. Why is the result not ready to use as a limit?
Show answer
Declare it as "max-lines": { type: "string" } inside options. For that input, values["max-lines"] is the string "10" and positionals is ["notes.txt"]. parseArgs never converts types, so the program must still convert the string to a number, for example with Number("10"). It must also check that the result is a valid whole number. A value like abc becomes NaN and must be rejected with a clear error message.