Sub topic 13
Reading from Standard Input
This chapter assumes you finished the earlier chapters. You have the wcl project with countText in src/count.ts, an entry point in src/cli.ts that reads a file, and a tsconfig.json using NodeNext. You should also be comfortable with async/await and know what a shell pipe is.
Until now, wcl only counts text in a named file. Unix tools usually also accept data on standard input (stdin), the stream a process reads when it has no file to open. With stdin support, these commands work:
printf 'a b\nc\n' | wcl
wcl - < notes.txt
curl -s https://example.com | wclWhat stdin is in Node.js
process.stdin is a readable stream. It is the same kind of object fs.createReadStream returns, so you can read it asynchronously. What it is connected to depends on how the user started the program:
| How the command is run | What stdin is connected to | `process.stdin.isTTY` | Column |
|---|---|---|---|
| `wcl` typed in a terminal | The keyboard | `true` | |
| `cat f \ | wcl` | The output of another process | `undefined` |
| `wcl < f` | A file | `undefined` |
Note that isTTY is undefined rather than false when stdin is not a terminal. Test it for truthiness, not with === false.
The TTY case matters. If a user runs wcl with no arguments and you start reading stdin, the program waits for keyboard input until the user presses Ctrl+D. That looks like a hang. The convention is to print a usage message and exit with code 2 instead.
Deciding where input comes from
Many tools follow a simple rule. If the file argument is missing or is a lone -, read stdin. Otherwise read the named file. A lone - is not a flag, so parseArgs returns it in positionals. Anything after a -- argument is also treated as positional.
Model the choice as a type, as you did with commands earlier. A discriminated union keeps the decision in one place and lets the compiler check it.
Reading all of stdin
The simplest way to read a stream into a string is text() from node:stream/consumers. It collects every chunk, decodes the bytes as UTF-8, and resolves when the stream ends.
Put the input logic in its own module, separate from the entry point. This follows the same rule as countText. The function takes the stream as a parameter, so tests can pass a fake stream and never touch the real process.stdin.
// src/input.ts
import { readFile } from "node:fs/promises";
import type { Readable } from "node:stream";
import { text } from "node:stream/consumers";
export type Source = { kind: "file"; path: string } | { kind: "stdin" };
export function chooseSource(arg: string | undefined): Source {
if (arg === undefined || arg === "-") {
return { kind: "stdin" };
}
return { kind: "file", path: arg };
}
export async function readSource(
source: Source,
stdin: Readable = process.stdin,
): Promise<string> {
switch (source.kind) {
case "file":
return readFile(source.path, "utf8");
case "stdin":
return text(stdin);
default: {
const unreachable: never = source;
return unreachable;
}
}
}The default argument process.stdin keeps normal calls short. Tests supply their own stream.
Why not concatenate chunks yourself
A hand-written version often looks like this:
let data = "";
for await (const chunk of process.stdin) {
data += chunk;
}This works only when chunks are strings. By default, stdin emits Buffer objects, and data += chunk converts each one to a string on its own. A multi-byte UTF-8 character can be split between two chunks, such as the two bytes of é. Decoding each half separately produces replacement characters (�). text() uses a streaming decoder that carries partial characters across chunk boundaries. If you want the manual loop, call process.stdin.setEncoding("utf8") first, which attaches the same kind of decoder.
Updating the entry point
Now main uses both modules. The TTY check goes in the entry point, not in readSource, because it depends on the real process. That keeps readSource testable.
// src/cli.ts
import { countText } from "./count.js";
import { chooseSource, readSource } from "./input.js";
async function main(argv: string[]): Promise<number> {
const source = chooseSource(argv[0]);
if (source.kind === "stdin" && process.stdin.isTTY) {
console.error("usage: wcl <file> (or pipe text into wcl)");
return 2;
}
try {
const input = await readSource(source);
const { lines, words } = countText(input);
const label = source.kind === "file" ? ` ${source.path}` : "";
console.log(`${lines} ${words}${label}`);
return 0;
} catch (err) {
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
console.error(`wcl: ${argv[0]}: no such file`);
} else {
console.error(`wcl: ${err instanceof Error ? err.message : String(err)}`);
}
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));The file keeps its shebang line from earlier chapters at the very top. The output for stdin has no name suffix, which matches what wc does. Try it after npm run build:
printf 'a b\nc\n' | node dist/cli.js
printf 'a b\nc\n' | node dist/cli.js -
node dist/cli.js < package.json
node dist/cli.js missing.txt; echo "exit: $?"The first two commands print 2 3. The last prints an error on stderr and exit: 1.
Edge cases to know
- Empty input.
printf '' | wclgives0 0.text()resolves to an empty string, andcountText("")already handles that case. - Stdin can be read once. After the stream ends, it cannot be rewound. If you need the text twice, keep the string.
- Closed stdin. Running
wcl < /dev/nullorwcl <&-ends the stream immediately or fails with an error. In both cases thetry/catchpath or the empty-input path handles it. - Binary data. Invalid UTF-8 bytes decode to
�. For a word counter that is acceptable. A byte-counting tool would need to readBuffers directly. - Slow producers.
yes | head -n 5 | wclworks becausetext()waits for the end of the stream. A producer that never ends, such asyes | wcl, makeswclwait forever and use more memory. That is how all tools that buffer input behave. - Broken pipes on output. If your output goes into a command like
headthat exits early, a write can fail withEPIPE.wclprints one short line, so it is not a concern here. A tool that prints large output should handleerrorevents onprocess.stdout.
When buffering is the wrong choice
readSource holds the whole input in memory. That is fine for text files and typical pipes. For multi-gigabyte logs, process the stream incrementally. The readline module yields one line at a time:
import { createInterface } from "node:readline";
import type { Readable } from "node:stream";
export async function countLinesStreaming(input: Readable): Promise<number> {
let lines = 0;
const rl = createInterface({ input, crlfDelay: Infinity });
for await (const _line of rl) {
lines++;
}
return lines;
}The trade-off is that the logic now depends on a stream, so it is harder to keep as a pure function. Also, readline counts a final line that has no trailing newline, while countText follows the stricter wc rule and does not. Word counting incrementally needs extra state, because a word can be split across chunks. For wcl, buffering keeps the code simpler, and the memory cost is acceptable.
Testing the input module
Because readSource takes a stream argument, a test can supply Readable.from. No real stdin or child process is needed. The second test splits a two-byte character across chunks to check the decoder behavior described earlier.
// src/input.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { Readable } from "node:stream";
import { chooseSource, readSource } from "./input.js";
test("no argument or a dash means stdin", () => {
assert.deepEqual(chooseSource(undefined), { kind: "stdin" });
assert.deepEqual(chooseSource("-"), { kind: "stdin" });
});
test("a name means a file", () => {
assert.deepEqual(chooseSource("notes.txt"), {
kind: "file",
path: "notes.txt",
});
});
test("reads text split across chunks", async () => {
const stream = Readable.from(["a b\n", "c\n"]);
assert.equal(await readSource({ kind: "stdin" }, stream), "a b\nc\n");
});
test("keeps a multi-byte character split between chunks", async () => {
const stream = Readable.from([Buffer.from([0xc3]), Buffer.from([0xa9])]);
assert.equal(await readSource({ kind: "stdin" }, stream), "é");
});Run npm test. It compiles and runs both this file and the count tests.
Common mistakes
- Reading stdin when the user gave no arguments in a terminal, which looks like a hang.
- Using
chunk.toString()per chunk and corrupting multi-byte characters. - Treating
isTTY === falseas the pipe test. The value isundefinedfor pipes. - Calling
process.exit()after output. Settingprocess.exitCodelets pending writes finish, as in the earlier error-handling chapter. - Reading
process.stdininside the pure counting function. This makes tests depend on the process.
Exercise
A user runs wcl with no arguments in an interactive terminal. Which line of the entry point stops the program from waiting for keyboard input, and what exit code does it return?
Show answer
The check source.kind === "stdin" && process.stdin.isTTY runs before any read. It prints a usage message to stderr and returns 2, so readSource is never called.
Exercise
Why does readSource accept a Readable parameter with a default of process.stdin, instead of reading process.stdin directly?
Show answer
A test can pass Readable.from([...]) and check the result without a real terminal, pipe, or child process. The default keeps the production call short, and readSource stays free of hidden dependencies on the process.
Exercise
Write the one-line change to chooseSource so that an empty string argument (wcl "") is treated as a usage error instead of a file name. What should chooseSource return, and what would you change in its type?
Show answer
Add a case such as { kind: "invalid" } to the Source union and return it when arg === "". The never check in readSource then fails to compile until you handle the new case there, for example by throwing an error with a clear message. That compile error is the reason to model the choice as a union.