Sub topic 10
Keeping logic separate from the entry point
This chapter splits the wcl tool into a pure counting module and a thin entry file. It assumes you have the project from the earlier chapters: a tsconfig.json using NodeNext, a package.json with "type": "module", and a src/cli.ts that reads a file and prints counts. You should be comfortable with async/await and ES module imports.
Why the split matters
A first version of a command-line tool often puts everything in one file. It parses arguments, reads the file, counts words, formats the result and prints it. That works until you want to test it.
The problem is that the entry file does things when it is loaded. It reads process.argv, touches the file system, writes to the terminal and sets the exit code. If a test imports that file to call one function, all of those effects run as well.
The fix is a dependency rule: the entry point may import logic, and logic never imports the entry point or reads from the process. The entry point does all the talking to the outside world. The rest of the code takes values and returns values.
Only cli.ts has arrows to the file system and the process. count.ts has none, so a test can use it without setting anything up.
What counts as pure here
A pure function returns the same output for the same input and has no side effects. In this tool, that means a function that does not:
- read or write files,
- read
process.argv,process.envor standard input, - call
console.logorconsole.error, - set
process.exitCodeor callprocess.exit, - read the clock or generate random numbers.
The counting function from the earlier chapters meets all of these rules:
export 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 };
}It takes a string and returns an object. It does not know whether the string came from a file, from standard input or from a test.
Moving formatting out of the entry point
Counting is already separate. The next piece of logic still inside main is the output format: the template string that builds "2 3 notes.txt". It depends only on the counts, the file name and the -l flag, so it can be a pure function too.
Here is src/count.ts with a named Counts type and a formatter added:
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 };
}
export function formatCounts(
counts: Counts,
file: string,
linesOnly: boolean,
): string {
return linesOnly
? `${counts.lines} ${file}`
: `${counts.lines} ${counts.words} ${file}`;
}formatCounts returns a string and does not print it. That choice keeps the function testable. A function that calls console.log internally can only be tested by intercepting the console. A function that returns a string can be tested with one assertion.
The thin entry point
With the logic moved out, src/cli.ts only wires things together:
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
import { parseArgs } from "node:util";
import { countText, formatCounts } from "./count.js";
async function main(argv: string[]): Promise<number> {
try {
const { values, positionals } = parseArgs({
args: argv,
options: {
lines: { type: "boolean", short: "l" },
help: { type: "boolean", short: "h" },
},
allowPositionals: true,
});
const file = positionals[0];
if (values.help || !file) {
console.error("usage: wcl [-l] <file>");
return values.help ? 0 : 2;
}
const text = await readFile(file, "utf8");
console.log(formatCounts(countText(text), file, values.lines ?? false));
return 0;
} catch (err) {
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
console.error("wcl: no such file");
} else {
console.error(`wcl: ${err instanceof Error ? err.message : String(err)}`);
}
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));Several details in this file are deliberate:
mainreceivesargvas a parameter and passes it toparseArgsthrough theargsoption. By defaultparseArgsreadsprocess.argvitself. Passing the array explicitly means only the last line of the file touches the global.mainreturns a number instead of callingprocess.exit. Callingprocess.exitcan cut off output that is still being written to a pipe. Assigningprocess.exitCodelets the process end on its own once output is flushed.- Unknown flags make
parseArgsthrow an error. Thetryblock covers it, so a typo like--lnesbecomes a message and exit code 1, not an uncaught exception. - The
.jsextension in"./count.js"is required underNodeNext, even though the source file iscount.ts. TypeScript resolves it to the.tsfile when compiling, and Node resolves it to the compiled.jsfile at run time.
The entry point has few branches and holds no counting rules. Most of the correctness risk is now in count.ts, where tests are cheap.
Why you cannot test the entry file directly
You might be tempted to export main from cli.ts and import it in a test. That does not work with this layout.
The last line of cli.ts runs main as soon as the module loads. Importing the file would run a full command using the test runner's own process.argv, print usage text to stderr, and set process.exitCode to 2. The test process would then exit with a failure code even if every assertion passed.
There are two common ways to handle this:
| Approach | How it works | Trade-off |
|---|---|---|
| Thin entry, test only the logic | Keep `cli.ts` to a few lines of wiring and test `count.ts`. | Simple. The wiring itself is untested. |
| Separate `run` module | Move `main` to `src/run.ts` with no top-level side effects, and have `cli.ts` import and call it. | Lets you test argument handling and exit codes, at the cost of one more file. |
For a tool this size, the first approach is enough. If main grows branches you want to test, the second is a small move: run.ts exports main, and cli.ts shrinks to the shebang, one import and the process.exitCode line.
Testing the pieces that moved
The new formatter gets tests alongside the counting tests. These go in src/count.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { countText, formatCounts } 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 });
});
test("a final line without a newline still counts", () => {
assert.deepEqual(countText("a b"), { lines: 1, words: 2 });
});
test("blank lines in the middle count as lines", () => {
assert.deepEqual(countText("a\n\nb\n"), { lines: 3, words: 2 });
});
test("formats all counts by default", () => {
assert.equal(formatCounts({ lines: 2, words: 3 }, "notes.txt", false), "2 3 notes.txt");
});
test("formats only lines when requested", () => {
assert.equal(formatCounts({ lines: 2, words: 3 }, "notes.txt", true), "2 notes.txt");
});None of these tests creates a file, sets an environment variable or captures output. Each one runs in well under a millisecond. The third and fourth tests pin down edge cases in the line-counting rule. If you later change countText, they show whether you changed behavior on purpose.
Run them with the test script from package.json:
npm testCommon mistakes
- Reading
process.argvinside logic. A function that reads it cannot be tested with different arguments without changing global state. Pass values in as parameters. - Printing from the logic layer. If
countTextcalledconsole.log, you could not reuse it in a program that wants the numbers instead of a printed line. - Importing upward. If
count.tsimported something fromcli.ts, loading the logic would also run the command. Keep the arrows in the diagram pointing one way. - Catching errors too deep. Logic functions should throw or return values and let the entry point decide on messages and exit codes. This keeps all user-facing error text in one place.
- Splitting too early. Not every function needs its own file. Move code out when it has rules worth testing, not just to shrink the entry file.
Checking your result
You can confirm the split works by checking three things:
grep -n "process\|console" src/count.tsfinds nothing.npm testpasses without reading any file from disk.node dist/cli.js -l notes.txtstill prints a line count and a file name, andecho $?prints0.
If all three hold, the logic layer is independent of the process, and the entry point is small enough to read at a glance.
Exercise
A teammate exports main from src/cli.ts and writes a test that imports it. The test passes its assertions but the test run still fails with exit code 2. Why does this happen, and how would you restructure the code so the test can call main safely?
Show answer
The last line of cli.ts, process.exitCode = await main(process.argv.slice(2)), runs when the module is imported. It calls main with the test runner's arguments, which have no file, so main prints usage to stderr and returns 2, and that value is stored in process.exitCode. The process then exits with 2 even though the assertions passed. To fix it, move main into a module such as src/run.ts that has no top-level side effects and exports it. Then cli.ts contains only the shebang, an import of main from ./run.js, and the process.exitCode = await main(process.argv.slice(2)) line. The test imports run.js, never cli.js.
Exercise
Add a pure function formatCounts variant that supports a --words flag, and name two tests you would write for it before changing cli.ts.
Show answer
Extend the options in parseArgs with words: { type: "boolean", short: "w" } and pass a mode value to a pure function such as formatCounts(counts, file, mode) where mode is "all" | "lines" | "words". It returns "${counts.words} ${file}" for "words". Two tests: formatCounts({ lines: 2, words: 3 }, "notes.txt", "words") returns "3 notes.txt", and formatCounts({ lines: 0, words: 0 }, "empty.txt", "words") returns "0 empty.txt". Both run without touching the file system, and cli.ts only changes to select the mode from the parsed flags.