Sub topic 2
Validating Input at the Boundary
Assume you know basic TypeScript, async/await, Node.js, and how to run npm scripts. A command-line program should validate external input before its core logic uses it. process.argv is external input, even when the user runs the command locally.
Validate arguments first
Node’s node:util module provides parseArgs for flags and positional arguments. After parsing, check the rules your command requires:
--helpmay appear without a file.- The counting command requires exactly one file.
- Unknown options should produce an error.
- Invalid input should return a usage error instead of crashing later.
import { parseArgs } from "node:util";
import { readFile } from "node:fs/promises";
type Command =
| { kind: "help" }
| { kind: "count"; file: string; linesOnly: boolean };
function parseCommand(argv: string[]): Command {
const { values, positionals } = parseArgs({
args: argv,
options: {
help: { type: "boolean", short: "h" },
lines: { type: "boolean", short: "l" },
},
allowPositionals: true,
strict: true,
});
if (values.help) {
return { kind: "help" };
}
if (positionals.length !== 1) {
throw new Error("usage: wcl [-l] <file>");
}
return {
kind: "count",
file: positionals[0],
linesOnly: values.lines ?? false,
};
}
async function main(argv: string[]): Promise<number> {
let command: Command;
try {
command = parseCommand(argv);
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
return 2;
}
if (command.kind === "help") {
console.log("usage: wcl [-l] <file>");
return 0;
}
try {
const text = await readFile(command.file, "utf8");
const lines = text === "" ? 0 : text.split("\n").length;
console.log(command.linesOnly ? lines : `${lines} ${command.file}`);
return 0;
} catch (error) {
console.error(
`wcl: ${command.file}: ${
error instanceof Error ? error.message : String(error)
}`,
);
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));Model valid commands with types
Command is a discriminated union. The kind field identifies the command, so TypeScript permits file and linesOnly only for the "count" case. This keeps validation at the boundary and keeps later code simple.
Use stdout and stderr deliberately
Write normal results and help text to standard output, called stdout. Write diagnostics to standard error, called stderr. This lets users redirect results without mixing them with failures.
Read files asynchronously
readFile returns a promise and does not block the event loop while the operating system reads the file. The try/catch around await readFile(...) converts file-system failures into a useful message and a nonzero exit code.
Exercise
Why should a file-read failure use exit code 1 instead of exit code 0?
Show answer
Exit code 0 means success. A nonzero code lets shells and scripts detect that the command failed.