Sub topic 5
Validating input at the boundary
This chapter assumes you can read the parseArgs call from the previous chapter and that you know TypeScript unions and try/catch. It covers how to turn raw command-line text into input the rest of the program can trust.
Why validate at the boundary
Everything a user types arrives as strings in process.argv. TypeScript cannot check those strings, because types exist only at compile time. A signature like file: string says nothing about whether the user supplied a file at all.
The boundary is the point where untrusted data enters your program. For a command-line tool, that is the code between process.argv and your core logic. The rule is to check input once, at that point, and then pass on values whose types already prove they are valid. Code past the boundary then needs no defensive checks, and error messages come from one place.
Validation here has two jobs:
- Reject input that is malformed: unknown flags, missing arguments, too many arguments.
- Produce a typed value, the
Commandfrom the next chapter, so the compiler enforces what you checked.
What parseArgs already checks
parseArgs runs in strict mode by default. In strict mode it throws an error in these cases:
- An option is not declared in
options. - A
stringoption has no value. - A
booleanoption is given a value, as in--lines=3. - A positional argument appears while
allowPositionalsis false.
The thrown error has a code property such as ERR_PARSE_ARGS_UNKNOWN_OPTION, and its message is readable. Do not set strict: false to avoid these errors. That mode silently accepts anything, and the typed values object loses its guarantees.
The call below shows the behavior. It passes args explicitly instead of reading process.argv, which also makes it testable.
import { parseArgs } from "node:util";
try {
parseArgs({
args: ["--colour"],
options: { lines: { type: "boolean", short: "l" } },
allowPositionals: true,
});
} catch (err) {
if (err instanceof Error && "code" in err) {
console.log(err.code); // ERR_PARSE_ARGS_UNKNOWN_OPTION
}
console.log(err instanceof Error ? err.message : String(err));
}parseArgs checks the syntax of the flags. It does not know how many positional arguments your command accepts, so you must check that yourself.
The validation pipeline
Validation runs in a fixed order. Each step either fails with a usage message or hands a narrower value to the next step.
The help flag is checked before the positional count. A user who types wcl --help has no file argument, and that must not be an error.
Returning a result instead of throwing
The validator needs a way to report failure. Throwing works, but you then have to catch the error and tell expected failures (bad input) from unexpected ones (bugs). A small result type makes the two cases explicit, and the compiler forces the caller to handle both.
import { parseArgs } from "node:util";
export type Command =
| { kind: "help" }
| { kind: "count"; file: string; linesOnly: boolean };
export type ParseResult =
| { ok: true; command: Command }
| { ok: false; message: string };
function fail(message: string): ParseResult {
return { ok: false, message };
}
function validate(
values: { lines?: boolean; help?: boolean },
positionals: string[],
): ParseResult {
if (values.help) {
return { ok: true, command: { kind: "help" } };
}
if (positionals.length === 0) {
return fail("missing file argument");
}
if (positionals.length > 1) {
return fail(`expected one file, got ${positionals.length}`);
}
const file = positionals[0];
if (file === "") {
return fail("file name must not be empty");
}
return {
ok: true,
command: { kind: "count", file, linesOnly: values.lines ?? false },
};
}
export function parseCommand(argv: string[]): ParseResult {
try {
const { values, positionals } = parseArgs({
args: argv,
options: {
lines: { type: "boolean", short: "l" },
help: { type: "boolean", short: "h" },
},
allowPositionals: true,
});
return validate(values, positionals);
} catch (err) {
return fail(err instanceof Error ? err.message : String(err));
}
}Three design choices are worth noting:
validatenever throws. Thetryblock therefore catches only errors fromparseArgs, and a bug invalidateis not reported as a usage error.validateis separate fromparseCommand. It takes plain data, so you can read the rules without theparseArgsconfiguration around them.values.lines ?? falseturnsboolean | undefinedintobooleanhere, so thecountcommand never carries anundefined.
Put this code in its own module, for example src/parse.ts. The next chapter develops the Command type further.
Wiring it into the entry point
The entry point calls parseCommand, reports failures to stderr, and returns exit code 2. By convention, 2 means incorrect usage, and 1 means the command ran and failed.
import { parseCommand } from "./parse.js";
async function main(argv: string[]): Promise<number> {
const result = parseCommand(argv);
if (!result.ok) {
console.error(`wcl: ${result.message}`);
console.error("Try: wcl --help");
return 2;
}
const { command } = result;
if (command.kind === "help") {
console.log("usage: wcl [-l] <file>");
return 0;
}
console.log(`would count ${command.file}`);
return 0;
}
process.exitCode = await main(process.argv.slice(2));After the ok check, TypeScript narrows result so that result.command exists. Without the check, accessing result.command is a compile error. The check also covers the failure branch for every caller that handles a ParseResult.
What counts as valid
Run the tool against these inputs and compare the outcome:
| Arguments | Outcome | Reason |
|---|---|---|
| `notes.txt` | count, all fields | One positional |
| `-l notes.txt` | count, lines only | Short flag accepted |
| `notes.txt -l` | count, lines only | Flags may follow positionals |
| `--help` | help | Checked first |
| (none) | usage error, exit 2 | No file |
| `a.txt b.txt` | usage error, exit 2 | Too many files |
| `--colour a.txt` | usage error, exit 2 | Unknown option from `parseArgs` |
| `--lines=3 a.txt` | usage error, exit 2 | Boolean option given a value |
| `-- -odd.txt` | count of a file named `-odd.txt` | Everything after `--` is positional |
The last row matters. A file name that begins with a dash is ambiguous unless the user writes --. parseArgs implements that convention, so you get it without extra code.
What not to validate here
Do not check whether the file exists at this point. The boundary check covers the shape of the input, and file existence is a fact about the world that can change. If you call access or existsSync first and then read, the file can disappear between the two calls. The check also duplicates what readFile already reports. Let the read fail and handle the error code, which the file I/O and error handling chapters cover.
Write messages that name the problem and the tool, as wcl: missing file argument does. Users often run tools inside scripts, where the prefix shows which program produced the line.
Validating values of other types
wcl has only boolean flags, so parseArgs gives you finished values. If you later add an option such as --max-lines, the value arrives as a string, and you must convert it yourself. Be careful with the conversion. Number("") is 0, Number("12abc") is NaN, and parseInt("12abc") is 12, which silently accepts garbage. A strict helper avoids all of these:
export function parsePositiveInt(
name: string,
raw: string,
): { ok: true; value: number } | { ok: false; message: string } {
if (!/^[0-9]+$/.test(raw)) {
return { ok: false, message: `${name} must be a whole number, got "${raw}"` };
}
const value = Number(raw);
if (!Number.isSafeInteger(value) || value < 1) {
return { ok: false, message: `${name} must be at least 1, got "${raw}"` };
}
return { ok: true, value };
}The regular expression rejects signs, decimals, whitespace, and trailing text before any conversion happens. The isSafeInteger check rejects values too large to represent exactly.
Testing the validator
Because parseCommand takes an array and returns a value, you can test it without a process or a file system. These tests use the same node:test setup the testing chapter describes.
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseCommand } from "./parse.js";
test("accepts a single file", () => {
assert.deepEqual(parseCommand(["a.txt"]), {
ok: true,
command: { kind: "count", file: "a.txt", linesOnly: false },
});
});
test("reads the lines flag", () => {
assert.deepEqual(parseCommand(["-l", "a.txt"]), {
ok: true,
command: { kind: "count", file: "a.txt", linesOnly: true },
});
});
test("rejects a missing file", () => {
const result = parseCommand([]);
assert.equal(result.ok, false);
});
test("rejects unknown options", () => {
const result = parseCommand(["--nope", "a.txt"]);
assert.equal(result.ok, false);
});
test("treats text after -- as a file name", () => {
assert.deepEqual(parseCommand(["--", "-l"]), {
ok: true,
command: { kind: "count", file: "-l", linesOnly: false },
});
});Common mistakes
- Setting
strict: false. Unknown flags then become silent no-ops, so a typo like--lineruns the wrong command. - Reading
process.argvinside the validator. Passargvin as a parameter. Otherwise you cannot test it. - Forgetting
slice(2).process.argv[0]is the Node binary and[1]is the script path. Both would count as positional arguments and trip the "too many files" rule. - Using exit code 1 for usage errors. Scripts cannot then tell "bad invocation" from "file missing". Reserve 2 for usage.
- Printing errors with
console.log. Error text on stdout corrupts output that another program is reading. Useconsole.error.
Exercise
You add a --max-lines <n> option of type string to parseArgs. A user runs wcl --max-lines 12abc a.txt. Which approach correctly rejects this input, and why does parseInt not?
Show answer
Validate the raw string with a strict check before converting, for example the regular expression /^[0-9]+$/ followed by Number and Number.isSafeInteger, as in parsePositiveInt. parseInt("12abc") returns 12, because it stops at the first non-digit and ignores the rest, so the bad input would be accepted. The failure should come back as a { ok: false } result and the entry point should exit with code 2.
Exercise
Why does parseCommand return { ok: false, message } for a bad invocation instead of calling process.exit(2) directly?
Show answer
Calling process.exit inside the validator would end the test process and make the function impossible to unit test. It would also skip any pending stdout writes and hide the decision about the exit code inside parsing code. Returning a result lets the entry point decide what to print and which code to return, and lets tests assert on the outcome.