Sub topic 3
Handling Errors and Setting Exit Codes
Assume you know basic TypeScript, async/await, Node.js, npm, and package.json. The earlier chapters created a strict Node.js ESM project and a command that accepts a file path.
Handling Errors and Setting Exit Codes
A command-line program communicates success through its exit code. 0 means success. A nonzero value means failure. Use standard output, stdout, for results and standard error, stderr, for diagnostics.
import { readFile } from "node:fs/promises";
function countText(text: string) {
return {
lines: text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0),
words: text.split(/\s+/).filter(Boolean).length,
};
}
async function main(argv: string[]): Promise<number> {
const file = argv[0];
if (!file) {
console.error("usage: wcl <file>");
return 2;
}
try {
const text = await readFile(file, "utf8");
const result = countText(text);
console.log(`${result.lines} ${result.words} ${file}`);
return 0;
} catch (error) {
const code = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined;
console.error(code === "ENOENT" ? `wcl: ${file}: no such file` : String(error));
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));Assigning process.exitCode lets Node flush pending output before it exits. Avoid calling process.exit() deep inside application code.
Keeping Logic Separate from the Entry Point
Keep counting in a pure function. A pure function depends only on its arguments and performs no file or process I/O. This makes its behavior easy to test. The entry point should coordinate parsing, I/O, output, and exit codes.
Testing the Core Logic
Node includes a test runner. Test boundary cases without starting a process or creating files.
import { test } from "node:test";
import assert from "node:assert/strict";
import { countText } from "./count.js";
test("counts lines and words", () => {
assert.deepEqual(countText("a b\nc\n"), { lines: 2, words: 3 });
});
test("empty input has no lines or words", () => {
assert.deepEqual(countText(""), { lines: 0, words: 0 });
});Run tests against the compiled JavaScript:
npm run build
node --test distPackaging and Running the Command
The bin field maps a command name to the compiled entry point.
{
"type": "module",
"bin": { "wcl": "dist/cli.js" },
"scripts": {
"build": "tsc",
"test": "tsc && node --test dist"
}
}After building, run npm link during local development. The wcl command then runs your compiled program.
Reading from Standard Input
A useful extension is reading piped data when no file is supplied. Node exposes standard input as process.stdin. Read it asynchronously, then pass the text to the same pure function.
let input = "";
for await (const chunk of process.stdin) input += chunk;
console.log(countText(input).words);Exercise
Why should the entry point return an exit code instead of calling process.exit()?
Show answer
Returning an exit code keeps process control centralized and gives pending output time to flush.