Sub topic 10
Keeping Logic Separate from the Entry Point
This chapter assumes you know basic TypeScript, async/await, Node.js, and how the earlier chapters configured a TypeScript project for Node.js ESM.
A command-line program usually has two kinds of work:
- Process work reads arguments, opens files, writes output, and chooses an exit code.
- Application work transforms input into a result.
Keeping these responsibilities separate makes the application work easier to test. It also prevents the entry point from becoming a large function that is difficult to change.
Put the counting logic in its own module
Create src/count.ts with a pure function. A pure function depends only on its arguments and does not read files, write output, or change global state.
export type Counts = {
lines: number;
words: number;
};
export function countText(text: string): Counts {
const lines =
text === ""
? 0
: text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
const words = text.split(/\s+/).filter(Boolean).length;
return { lines, words };
}The function treats a final newline as a separator rather than an additional empty line. For example, "one\ntwo\n" contains two lines. The regular expression \s+ matches one or more whitespace characters, so spaces, tabs, and newlines separate words.
Because countText has no file-system dependency, a test can call it directly with a string.
Let the entry point coordinate effects
The entry point should translate the outside world into values that the application logic can use. It can then translate the result back into terminal output.
Create src/cli.ts:
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
import { countText } from "./count.js";
export 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 { lines, words } = countText(text);
console.log(`${lines} ${words} ${file}`);
return 0;
} catch (error: unknown) {
if (
error instanceof Error &&
"code" in error &&
error.code === "ENOENT"
) {
console.error(`wcl: ${file}: no such file`);
} else {
console.error(
`wcl: ${error instanceof Error ? error.message : String(error)}`,
);
}
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));main receives argv instead of reading process.argv itself. This small design choice makes it possible to test argument handling without starting a child process.
The function returns a number rather than calling process.exit. Assigning the result to process.exitCode lets Node.js finish pending output and asynchronous cleanup before it exits.
| Responsibility | Location | Example |
|---|---|---|
| Read a file | `main` | `readFile(file, "utf8")` |
| Count words | `countText` | `countText(text)` |
| Print a result | `main` | `console.log(...)` |
| Choose a status | `main` | `return 0` or `return 1` |
See the boundary between effects and logic
Test the pure module
Create src/count.test.ts:
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 the project’s build and test scripts:
npm testThese tests do not create temporary files or capture terminal output. They check the important counting rules directly, so a failure points to countText rather than to unrelated file-system behavior.
Exercise
Why should countText return counts instead of printing them?
Show answer
Returning counts keeps the function pure and reusable. The command entry point can choose how to format or display the result, while tests can compare the returned object directly.