Working with stdin and stdout
1. Reading from stdin (process.stdin)
Example: Async iterator
process.stdin.setEncoding("utf8");
for await (const chunk of process.stdin) {
console.log("got:", chunk);
}
| Event | Fires |
data | Chunk available |
end | EOF |
readable | Use with read() |
2. Writing to stdout (process.stdout)
| Method | Notes |
process.stdout.write(str) | No newline added |
console.log | Adds newline + format |
process.stdout.isTTY | True if interactive |
3. Writing to stderr (process.stderr)
Example
process.stderr.write("error happened\n");
console.error("structured error", { code: 42 });
| Event | Use |
data | Streamed chunks |
end | Stdin closed (Ctrl+D) |
error | I/O failure |
5. Piping Data Between Streams
Example: Uppercase pipeline
import { Transform, pipeline } from "node:stream";
import { promisify } from "node:util";
const upper = new Transform({
transform(chunk, _, cb) { cb(null, chunk.toString().toUpperCase()); }
});
await promisify(pipeline)(process.stdin, upper, process.stdout);
6. Setting Raw Mode (setRawMode)
| Mode | Effect |
setRawMode(true) | Reads keystrokes immediately, no buffering, no Ctrl+C handling |
setRawMode(false) | Line-buffered (default) |
7. Using TTY Module (tty.isatty)
| API | Returns |
tty.isatty(fd) | Boolean |
process.stdout.isTTY | Shortcut for stdout |
process.stdin.isTTY | Detect piped input |
8. Detecting Terminal Size (process.stdout.columns)
| Property | Returns |
process.stdout.columns | Width in cols |
process.stdout.rows | Height in rows |
"resize" event | Fires on terminal resize |
9. Handling ANSI Colors
| Code | Effect |
\x1b[31m / \x1b[0m | Red / reset |
\x1b[1m | Bold |
chalk / picocolors | Idiomatic libraries |
Note: Disable colors when !process.stdout.isTTY or process.env.NO_COLOR is set.
10. Creating Progress Bars
Example: Manual bar
function bar(pct) {
const w = 30, filled = Math.round(w * pct);
process.stdout.write(`\r[${"#".repeat(filled)}${"-".repeat(w-filled)}] ${(pct*100).toFixed(0)}%`);
}
| Library | Use |
cli-progress | Multi-bar, ETA |
ora | Spinners |
listr2 | Task lists |