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();
OptionPurpose
input / outputStreams
terminalForce TTY behavior
completerTab completion fn
historyPre-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)

APIBehavior
rl.question(q, cb)Callback variant
await rl.question(q)Promise variant (readline/promises)

4. Writing Prompts (rl.prompt)

MethodUse
rl.setPrompt("> ")Set prompt string
rl.prompt()Display prompt
Event lineFires for each entered line

5. Pausing Input (rl.pause)

MethodEffect
rl.pause()Stop emitting line events

6. Resuming Input (rl.resume)

MethodEffect
rl.resume()Re-enable line events

7. Closing Interface (rl.close)

TriggerBehavior
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

PatternResult
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));

11. Implementing Auto-Completion

Example: Completer fn

function completer(line) {
  const cmds = ["help", "list", "load", "save", "exit"];
  const hits = cmds.filter((c) => c.startsWith(line));
  return [hits.length ? hits : cmds, line];
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, completer });