Sub topic 3
Writing the entry point
The entry point is the file Node runs first. It connects your program to the operating system: it receives the arguments, decides the exit code, and hands the real work to other code. This chapter builds src/cli.ts for the wcl tool and covers the choices that keep it small and reliable.
This chapter assumes you finished the project setup and tsconfig.json chapters. You have a package.json with "type": "module", a tsconfig.json using NodeNext, and @types/node installed. You should also be comfortable with async/await.
What the entry point is responsible for
An entry point does a few things that other modules should not:
- It is the only place that reads
process.argv. - It is the only place that sets the exit code.
- It starts the program as a side effect when the file is run.
Everything else, such as counting and formatting, lives in modules that other code can import without anything running. That split matters for testing, and a later chapter returns to it. For now, keep the entry point thin and put it in src/cli.ts.
The shebang line
On Linux and macOS, a text file can run as a program if its first line names an interpreter. That line is the shebang (also called a hashbang). It starts with #!.
#!/usr/bin/env node
console.log("hello from wcl");The line #!/usr/bin/env node asks the system to run env node, which finds node on your PATH and runs the file with it. This is more portable than hard-coding a path such as /usr/local/bin/node, because Node is installed in different places on different machines, especially with version managers.
The TypeScript compiler accepts a shebang on the first line of a .ts file and copies it unchanged to the .js output. You write it once in the source, and it appears in dist/cli.js.
Some details about shebangs:
- It must be the very first line. A blank line or a byte-order mark before it breaks it.
- The file must use Unix line endings (
\n). With Windows line endings (\r\n), the system looks for an interpreter namednode\rand fails with an error likeenv: node\r: No such file or directory. If you edit on Windows, configure your editor or Git to keep\nin this file. - Node itself ignores the shebang line when you run
node dist/cli.js. It only matters when the system launches the file directly. - Windows does not read shebangs at all. When a user installs your package, npm generates small wrapper scripts (
.cmdand PowerShell shims) that call Node for them.
Why the file is an ES module
Your package.json has "type": "module", so Node treats every .js file in the package as an ES module. Your tsconfig.json has "module": "NodeNext", so TypeScript follows the same rule and emits import statements instead of require calls.
This has two consequences for the entry point.
First, relative imports need the compiled extension, even though the source file is .ts:
import { countText } from "./count.js";TypeScript does not rewrite import paths. Node will look for count.js at run time, so you write .js and TypeScript maps it to count.ts while type checking.
Second, you can use top-level await, meaning await outside any function. It works in ES modules when the target is ES2022 or later, which is what the tsconfig uses. The entry point uses it to wait for the main function.
What `process.argv` contains
process.argv is an array of strings describing how the process started.
| Index | Value | Example |
|---|---|---|
| 0 | Path to the Node executable | `/usr/local/bin/node` |
| 1 | Path to the script being run | `/home/you/wcl/dist/cli.js` |
| 2 and later | The arguments the user typed | `-l`, `notes.txt` |
The first two entries are about the runtime, not about your program's input. Calling process.argv.slice(2) gives you only what the user typed. The built-in parseArgs function from node:util does this slicing for you when you do not pass an args option, as the next chapter shows. Slicing by hand is still useful when you want to pass the arguments to your own function, which is the pattern in this chapter.
Every element is a string. The shell splits the command line before Node sees it, so wcl "my notes.txt" arrives as one argument, my notes.txt, with the quotes already removed.
A first runnable entry point
Here is a complete first version of src/cli.ts. It does not count anything yet. It shows the shape the finished file will keep.
#!/usr/bin/env node
async function main(argv: string[]): Promise<number> {
if (argv.length === 0) {
console.error("usage: wcl <file>");
return 2;
}
console.log(`received ${argv.length} argument(s): ${argv.join(", ")}`);
return 0;
}
process.exitCode = await main(process.argv.slice(2));Build and run it:
npm run build
node dist/cli.js notes.txt other.txt
echo "exit code: $?"
node dist/cli.js
echo "exit code: $?"The first run prints received 2 argument(s): notes.txt, other.txt and exit code 0. The second prints the usage message to standard error and exit code 2. The $? variable holds the exit code of the last command in POSIX shells such as bash and zsh.
The file has three parts.
- The shebang.
- A
mainfunction that takes the arguments as a parameter and returns a number. Because it receivesargvinstead of readingprocess.argvitself, you can call it from a test with any arguments you like. - One line at the bottom that connects
mainto the process.
Exit codes: `process.exitCode` or `process.exit()`
Every process ends with an exit code. By convention 0 means success and any other value means failure. Shells, make, and CI systems read this number to decide what to do next, so it is part of your tool's interface.
Node gives you two ways to set it:
| Approach | What happens | Risk |
|---|---|---|
| `process.exitCode = 1` | Records the code. The process ends naturally when pending work finishes. | None for normal use. |
| `process.exit(1)` | Ends the process immediately. | Pending writes to a pipe may be cut off, and cleanup that was still waiting never runs. |
The risk of process.exit() is real. When standard output is a pipe, as in wcl big.txt | head, Node may write to it asynchronously. Calling process.exit() right after a large console.log can lose part of the output. Setting process.exitCode lets Node drain its buffers and exit by itself.
The pattern used in this chapter avoids the problem. main returns a number, and the last line stores it in process.exitCode. No other code in the program calls process.exit().
The numbers used here follow a common convention: 0 for success, 1 for a runtime failure such as a missing file, and 2 for incorrect usage. Shells use 2 the same way for misused built-ins. The error handling chapter returns to this.
What happens when you run the command
The next diagram shows the path from the terminal to the exit code.
Handling a rejected promise
What happens if main throws an error you did not expect? Because main is async, the error becomes a rejected promise. With top-level await, that rejection stops the module from loading. Node prints the stack trace to standard error and exits with code 1.
That is acceptable as a last resort, but a stack trace is a poor message for a user. A better design catches the errors you expect inside main, prints a short message, and returns a specific code. The unexpected ones still reach Node's default handler, which is useful: a crash with a stack trace shows you a bug instead of hiding it.
Do not wrap the whole entry point in a try/catch that prints "something went wrong" and returns 1. You would lose the stack trace and gain nothing.
Keeping the entry point from running during tests
Because process.exitCode = await main(...) runs as soon as the file loads, importing cli.ts from a test would start the program. This is why the counting logic goes in a separate module, count.ts, and tests import that file instead. The entry point stays small enough that you can check it by running it.
If you want to import main from tests, you have two options. You can move main into its own module and leave only the last line in cli.ts. Or you can guard the call by comparing import.meta.url with the script path. The first option is simpler and needs no path comparison, which behaves differently across symlinks. The code structure chapter uses it.
Common mistakes
- Reading
process.argv[0]as the first argument. It is the path to Node. User input starts at index 2. - Forgetting the
.jsextension in relative imports. TypeScript may type check without complaint in some setups, but Node fails at run time withERR_MODULE_NOT_FOUND. - Printing errors with
console.log. Errors belong on standard error. Useconsole.error. The next chapters cover the difference. - Calling
process.exit()after writing output. Setprocess.exitCodeinstead. - Running
./dist/cli.jsand getting "permission denied". A file you built yourself has no executable bit. Runchmod +x dist/cli.jsfor a quick test. When the package is installed or linked through thebinfield, npm sets the bit for you.
Summary
The entry point of wcl is a short file: a shebang, an async main(argv) that returns an exit code, and one line that assigns the result to process.exitCode. It reads process.argv in one place and has no counting logic in it. The next chapter fills in main by parsing flags and positional arguments with parseArgs.
Exercise
Your entry point ends with process.exit(await main(process.argv.slice(2))). A user runs wcl huge.txt | head -n 1 and sometimes sees truncated or missing output. Explain the cause and rewrite the last line to fix it. Also state what process.argv.slice(2) removes.
Show answer
When standard output is a pipe, Node can write to it asynchronously. process.exit() ends the process immediately, so output that is still buffered may never be written. The fix is to let Node exit on its own after flushing: process.exitCode = await main(process.argv.slice(2));. The call process.argv.slice(2) removes the first two entries, the path to the Node executable and the path to the script, leaving only the arguments the user typed.
Exercise
You compile src/cli.ts, which begins with #!/usr/bin/env node, and run ./dist/cli.js on Linux. The shell reports "permission denied". Running node dist/cli.js works. What is missing, and what command fixes it for a quick test?
Show answer
The compiled file lacks the executable permission bit. Node does not need it, but the system does when launching a file directly. Run chmod +x dist/cli.js. When the tool is installed or linked through the bin field in package.json, npm sets the bit automatically.