Sub topic 9
Handling Errors and Setting Exit Codes
Assume you know basic TypeScript, async/await, package.json, and how to run Node.js commands in a terminal. This chapter builds on an entry point that has already parsed command-line arguments.
A command-line program communicates its result in two ways:
- It writes human-readable text to standard output or standard error.
- It returns an exit code to the operating system.
An exit code is a number that describes whether the command succeeded. By convention, 0 means success. A nonzero value means failure. Many scripts and CI systems check this value instead of reading the printed message.
Use a main function that returns a code
Keep the program's work inside an asynchronous main function. Instead of calling process.exit() from several places, return a number from main and assign it to process.exitCode once.
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
function countText(text: string): { lines: number; words: number } {
const lines =
text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
const words = text.split(/\s+/).filter(Boolean).length;
return { lines, words };
}
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 (err) {
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
console.error(`wcl: ${file}: no such file`);
} else {
const message = err instanceof Error ? err.message : String(err);
console.error(`wcl: ${message}`);
}
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));The program returns 2 when the user gives invalid input, such as no file name. It returns 1 when it cannot read the requested file. It returns 0 after successful output.
The try block surrounds the operation that can fail. readFile rejects its promise when the file does not exist or cannot be read. The catch block converts that failure into a useful message and an exit code.
Understand stdout and stderr
console.log writes to standard output, often called stdout. It is for normal command results. console.error writes to standard error, or stderr. It is for diagnostics.
Keeping these streams separate lets users redirect results without also capturing errors:
wcl notes.txt > counts.txtThe count goes into counts.txt. An error still appears in the terminal. Scripts can also redirect the streams independently.
Avoid premature process.exit
Calling process.exit(1) immediately stops the process. It can prevent buffered output from being written and makes testing harder. Setting process.exitCode records the result while allowing Node.js to finish pending work.
Handle unknown thrown values
JavaScript permits throwing values that are not Error objects. For example, code could throw a string. The err instanceof Error check prevents unsafe access to .message. String(err) provides a fallback for other values.
Catch errors at the boundary where you can explain them to the user. Keep lower-level functions focused on their work. A file-reading helper can let its error reject; main can decide how that error should appear in a command-line interface.
Exercise
What exit code should the command return when the user omits the file argument, and where should the usage message be written?
Show answer
Return a nonzero usage-related code such as 2, and write the usage message to stderr with console.error.