Sub topic 7
Writing to stdout and stderr
A command-line program talks to the outside world through three standard streams. This chapter covers the two output streams. It shows how wcl should use each one, how to write to them correctly in Node.js, and which problems appear when output is piped or redirected.
You should already know how to write a TypeScript entry point (the previous chapters set one up) and be comfortable with basic shell redirection such as > and |. Reading from the third stream, standard input, comes in a later chapter.
The two output streams
Every process starts with numbered channels called file descriptors. Two of them carry output.
| Stream | File descriptor | Node.js object | Intended content |
|---|---|---|---|
| stdout | 1 | `process.stdout` | The program's result: data another program might read |
| stderr | 2 | `process.stderr` | Diagnostics: errors, warnings, progress, usage mistakes |
By default a terminal shows both streams interleaved, so they look the same. The difference appears when the user redirects one of them. wcl notes.txt > result.txt sends stdout to a file and leaves stderr on the screen. wcl notes.txt 2> errors.log does the opposite. In a pipeline like wcl notes.txt | sort, only stdout enters the pipe.
This routing is why the rule matters. If wcl printed an error message to stdout, that message would travel down the pipe and be treated as data by the next program. If it printed results to stderr, redirecting to a file would produce an empty file.
The convention is:
- Write the answer the user asked for to stdout.
- Write everything about the run itself to stderr.
console versus process.stdout
Node.js offers two ways to write. They reach the same streams.
console.logandconsole.infowrite to stdout.console.errorandconsole.warnwrite to stderr.process.stdout.write(text)andprocess.stderr.write(text)write exactly the string you pass.
console.log formats its arguments and appends a newline. process.stdout.write does not append anything, so you control every byte. For a tool whose output other programs parse, that precision is useful. It also avoids the surprise of console.log formatting non-string values with util.inspect.
A small output module keeps these decisions in one place. Create src/output.ts:
export const usage = "usage: wcl [-l] <file>";
const useColor = process.stderr.isTTY === true && !process.env.NO_COLOR;
export function print(message: string): void {
process.stdout.write(`${message}\n`);
}
export function printError(message: string): void {
const prefix = useColor ? "\x1b[31mwcl:\x1b[0m" : "wcl:";
process.stderr.write(`${prefix} ${message}\n`);
}Two details deserve attention.
First, print is the only place that writes results. The rest of the program calls it and never touches process.stdout directly. If you later need to change the format, add a --json flag, or capture output in a test, there is one function to change.
Second, printError adds color only when stderr is a terminal. process.stderr.isTTY is true when the stream is attached to a terminal and undefined when it is redirected to a file or a pipe. Escape codes such as \x1b[31m are noise in a log file. The NO_COLOR environment variable is a widely followed convention: if it is set to a non-empty value, the program should not emit color.
Note that the color decision looks at stderr, not stdout. The prefix is written to stderr, so stderr is the stream whose destination matters. A user can run wcl file > out.txt and still get colored errors on their screen.
Usage text: stdout or stderr?
Usage text is the one message that belongs to either stream, depending on why it is shown.
- When the user asks for help with
--help, the help text is the requested result. Write it to stdout and exit with code 0. This letswcl --help | lesswork. - When the user made a mistake, such as forgetting the file argument, the usage line is part of an error. Write it to stderr and exit with a non-zero code. By convention, 2 means incorrect usage.
Here is a short entry point that applies both rules. It uses parseArgs as in the earlier chapter, and passes the arguments in explicitly:
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { print, printError, usage } from "./output.js";
function main(argv: string[]): number {
const { values, positionals } = parseArgs({
args: argv,
options: {
help: { type: "boolean", short: "h" },
},
allowPositionals: true,
});
if (values.help) {
print(usage);
return 0;
}
if (positionals.length === 0) {
printError(usage);
return 2;
}
print(`would count ${positionals[0]}`);
return 0;
}
process.exitCode = main(process.argv.slice(2));After building, you can see the routing for yourself. The shell snippets below assume you ran npm run build and are in the project root.
# Help goes to stdout: it lands in help.txt, the terminal stays quiet.
node dist/cli.js --help > help.txt
# The usage error goes to stderr: the redirect captures nothing,
# and the message still appears on screen.
node dist/cli.js > out.txt
echo "exit code: $?"
# Redirect stderr instead, and the message goes to the file.
node dist/cli.js 2> err.txt
cat err.txtThe second command prints the usage error on your terminal even though stdout was redirected. It then prints exit code: 2. That is the behavior scripts rely on.
Why exit through process.exitCode
The entry point above sets process.exitCode and lets the function return. It does not call process.exit(). The difference affects output.
process.exit(code) ends the process immediately. If a write to stdout is still pending, that data can be lost. This is most likely when stdout is a pipe, because on some platforms pipe writes are asynchronous. A program that prints a large result and then calls process.exit(0) can appear to work in a terminal and truncate its output in a pipeline.
Setting process.exitCode tells Node what status to use, then lets the event loop drain naturally. Pending writes finish, and the process exits with your code once nothing is left to do.
Handling a closed pipe
There is one more case worth handling. When a user runs wcl big.txt | head -n 1, the head program exits after reading one line. The next time wcl writes to the now-closed pipe, the operating system reports a broken pipe. In Node.js this shows up as an error event on process.stdout with the code EPIPE. With no listener, Node throws, and the user sees a stack trace for what is a perfectly normal use.
Most Unix tools exit quietly in this situation. You can do the same by listening for the event once, near the top of the entry point:
process.stdout.on("error", (error: NodeJS.ErrnoException) => {
if (error.code === "EPIPE") {
process.exit(0);
}
throw error;
});Here process.exit(0) is acceptable. The reader has closed the pipe, so there is no output left to lose. Any other stream error is unexpected, so the handler rethrows it rather than hiding it.
For a tool that prints one line of output, as wcl does, this is rarely triggered. It becomes important if you extend the tool to print per-line results for large inputs.
Keep stdout clean
Stdout is a contract with whatever reads it. Some habits to keep that contract intact:
- Do not print debugging information with
console.log. Useconsole.errororprocess.stderr.write, and remove it before release. - Do not print progress messages, such as "Reading file...", to stdout. Either omit them or send them to stderr.
- Print one complete record per line, with consistent separators, so downstream tools like
sort,cut, andawkwork. - Do not mix human decoration, such as banners or colors, into stdout. If you want pretty output for terminals, decide based on
process.stdout.isTTY, and make sure the plain form is what gets produced when output is piped.
A quick test of discipline is to run your tool with stderr discarded and check that stdout alone is correct and complete:
node dist/cli.js notes.txt 2> /dev/nullIf anything useful is missing, it went to the wrong stream.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Errors written with `console.log` | Error text appears inside redirected output files | Use `printError` or `console.error` |
| Results written with `console.error` | `wcl file > out.txt` leaves `out.txt` empty | Send results through `print` |
| `process.exit(0)` right after a large write | Truncated output in a pipeline | Set `process.exitCode` instead |
| Color codes written unconditionally | Garbage like `[31m` in log files | Check `isTTY` and `NO_COLOR` |
| No handling of `EPIPE` | Stack trace when piping to `head` | Exit quietly on `EPIPE` |
Exercises
Exercise
A user runs wcl missing.txt > result.txt and the file does not exist. Which stream should carry the message "wcl: missing.txt: no such file", what will result.txt contain, and what will the user see on the terminal?
Show answer
The message belongs on stderr. result.txt will be empty, because nothing was written to stdout and only stdout was redirected. The user will see the error message on the terminal, because stderr was not redirected.
Exercise
Your tool prints a long report and then calls process.exit(0). Run as node dist/cli.js big.txt | wc -c, the byte count is sometimes lower than the real report size. Why does this happen, and what is the fix?
Show answer
process.exit() terminates the process immediately, so writes to the pipe that are still pending can be discarded. The fix is to set process.exitCode = 0 (or return a code from main and assign it to process.exitCode) and let the process end naturally, which gives Node time to flush stdout.