Working with Readline Interface
1. Creating Readline Interface (readline.createInterface)
Example: Basic interface
import readline from "node:readline/promises";
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const name = await rl.question("Name? ");
console.log(`Hi ${name}`);
rl.close();
| Option | Purpose |
|---|---|
input / output | Streams |
terminal | Force TTY behavior |
completer | Tab completion fn |
history | Pre-populate history |
2. Reading Line by Line
Example: Process file lines
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
const rl = createInterface({ input: createReadStream("big.log"), crlfDelay: Infinity });
for await (const line of rl) console.log(line);
3. Prompting for Input (rl.question)
| API | Behavior |
|---|---|
rl.question(q, cb) | Callback variant |
await rl.question(q) | Promise variant (readline/promises) |
4. Writing Prompts (rl.prompt)
| Method | Use |
|---|---|
rl.setPrompt("> ") | Set prompt string |
rl.prompt() | Display prompt |
Event line | Fires for each entered line |
5. Pausing Input (rl.pause)
| Method | Effect |
|---|---|
rl.pause() | Stop emitting line events |
6. Resuming Input (rl.resume)
| Method | Effect |
|---|---|
rl.resume() | Re-enable line events |
7. Closing Interface (rl.close)
| Trigger | Behavior |
|---|---|
rl.close() | Releases stdin; emits close |
EOF (Ctrl+D) | Auto-close |
8. Handling SIGINT
Example: Confirm exit
rl.on("SIGINT", async () => {
const answer = await rl.question("Quit? (y/n) ");
if (answer.toLowerCase() === "y") process.exit(0);
});
9. Using Async Iterators on Interface
| Pattern | Result |
|---|---|
for await (const line of rl) | Iterate lines, auto-pause/resume |
10. Creating Command-Line Interfaces
Example: REPL-style loop
rl.setPrompt("app> ");
rl.prompt();
rl.on("line", (line) => {
if (line === "exit") return rl.close();
console.log(`echo: ${line}`);
rl.prompt();
}).on("close", () => process.exit(0));