Sub topic 13
Reading from Standard Input
Assume you know basic TypeScript, async and await, Node.js streams, and how the earlier chapters’ countText function counts lines and words. This chapter adds standard input to the command-line tool.
Standard input, often called stdin, is a stream of data supplied to a program. It can come from a user typing in the terminal, another command, or redirected file contents. A command-line program can support both named files and stdin, which makes it useful in shell pipelines.
Choosing between a file and stdin
A common convention is that a single hyphen, -, means “read from standard input.” The program can then use either of these forms:
wcl notes.txt
wcl -
cat notes.txt | wclThe third command omits the argument, so this implementation also treats a missing file name as stdin.
Reading stdin asynchronously
Node.js exposes standard input as process.stdin. It is a readable stream, so the program receives data in chunks rather than necessarily receiving the entire input at once.
An asynchronous for await...of loop waits for each chunk without blocking the event loop. The loop ends when the input stream reaches end-of-file, called EOF. In a terminal, pressing Ctrl-D on macOS or Linux sends EOF. On Windows, Ctrl-Z followed by Enter usually sends EOF.
The following entry point accepts a file name, -, or no argument. It includes the counting function so the example can run as one file.
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
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 };
}
async function readStdin(): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
return Buffer.concat(chunks).toString("utf8");
}
async function readInput(source: string | undefined): Promise<string> {
if (source === undefined || source === "-") {
return readStdin();
}
return readFile(source, "utf8");
}
async function main(argv: string[]): Promise<number> {
const source = argv[0];
try {
const text = await readInput(source);
const { lines, words } = countText(text);
const label = source && source !== "-" ? source : "<stdin>";
console.log(`${lines} ${words} ${label}`);
return 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`wcl: ${message}`);
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));The chunks array stores each piece of input. Buffer.concat joins those pieces, and toString("utf8") converts the bytes into text. This approach works for redirected files and piped commands.
Using the command in a pipeline
After compiling the program, these commands send data to stdin:
printf "one two\nthree\n" | node dist/cli.js
node dist/cli.js - < notes.txtThe shell connects the output of printf or the contents of notes.txt to the program’s process.stdin. The program still writes its result to standard output, so another command can consume that result.
Keep diagnostic messages on stderr with console.error. This prevents errors from becoming part of data that a pipeline expects on stdout.
Exercise
Why should the program wait for EOF before counting stdin?
Show answer
Input arrives in multiple chunks, so counting before EOF could produce an incomplete result.