Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 133 ยท Compression, CLI and Tooling

Interactive CLIs with readline

Build interactive Node.js command-line programs with readline and readline/promises - prompts, reading stdin line by line, piped input, history, closing correctly and writing a small REPL.

A command-line program often needs to talk to a person or to another program: ask a question and wait for the answer, read a file of data line by line, or run a loop that accepts commands until the user types exit. In Node.js, the standard tool for this is the node:readline module. It turns the raw stream of bytes arriving on standard input (process.stdin) into clean lines of text, and gives you prompts, history and editing keys when a real terminal is attached.

This lesson teaches readline from the first prompt to a complete command REPL, and covers the traps that bite everyone once: input that arrives faster than you ask for it, forgetting to close the interface, and the difference between a person typing and a pipe feeding data. In the TryIt boxes the Input box is standard input, so you can type your own lines and press Run. Background: The process Object (stdin, stdout, exit codes) and Readable Streams.

Standard input as a stream

process.stdin is a readable stream. You can read it directly, but you receive arbitrary chunks, which may split a line in the middle or contain several lines at once. For a small program that reads everything, collecting the chunks is enough.

Node.js Reading all of stdin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

That works, but it waits for the end of input, so it cannot react to each line, and for a keyboard-driven program the input never ends until the user presses Ctrl+D. readline solves both problems.

Reading line by line

readline.createInterface({ input }) wraps a readable stream and emits a 'line' event for each complete line, with the line ending removed. When the stream ends it emits 'close'.

Node.js The line and close events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The program exits by itself because the input ended and nothing else keeps the event loop alive. With a keyboard, the input does not end, and the program would wait forever until the user pressed Ctrl+D (end of input) or Ctrl+C.

The modern way: for await

An interface is also an async iterable of lines, so you can write a plain loop. This is usually the clearest way to process input, because the loop body can await things and errors flow through try/catch. See Async Iterators.

Node.js Processing lines with for await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Remarks:

  • crlfDelay: Infinity is the recommended setting when files might come from Windows: it never splits \r\n into two lines.
  • Diagnostics go to console.error (standard error), so they do not mix with normal output when someone redirects it. More in Building Command-Line Tools.
  • This pattern streams: it holds one line at a time, so it processes a gigabyte log in constant memory. The same interface works on a file with createReadStream (see File Streams and CSV and Text Processing).

The input does not have to be stdin. Any readable stream works, which also makes code easy to test: feed it Readable.from([...]) instead of the keyboard.

Node.js Counting words in any stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that readline reassembled the cat sat on the mat from chunks that cut it in the middle. That is the main value of the module.

Asking questions with readline/promises

For interactive prompts, node:readline/promises gives you rl.question(text) that returns a promise of the answer. Pass process.stdin and process.stdout so the question is printed and the answer read.

Node.js A short interview with rl.question

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Why the helper instead of three plain await rl.question(...) calls? Because of a real pitfall, explained next.

The pipe pitfall: questions can lose lines

rl.question only works if the program is already waiting when the answer arrives. With a person at a keyboard that is always true. With piped input (a file, another program, or our Input box), all lines can arrive at once; those that come while no question is pending are emitted as ordinary 'line' events, which nobody listens to, and are lost. Then the next question waits forever, the input has ended, and Node exits with an unsettled top-level await.

Node.js Sequential question calls with piped input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You will see the first prompt, and then the program stops with a warning about an unsettled top-level await and the exit code 13 (the real warning reads "Detected unsettled top-level await" and points at the second question). If your tool is only ever used by people at a keyboard, plain question is fine. If it might be piped or tested with canned input, use the line-iterator helper from the previous example (or the 'line' event) instead. Writing tools that behave well in both modes is part of Building Command-Line Tools.

Using a closed interface

Another error you will meet: calling question after close(). Once closed, an interface cannot be reused, and Node says so clearly.

Node.js Using readline after close (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first attempt is caught and printed (ERR_USE_AFTER_CLOSE, "readline was closed"), the second one crashes the program with that error and a stack trace.

Prompts, loops and a command REPL

A REPL (read-eval-print loop) reads a command, runs it, prints the result and repeats. rl.setPrompt('> ') and rl.prompt() print the prompt and, on a terminal, put the cursor after it. Combine them with the 'line' event, or iterate lines and call prompt() after each command.

The program below is a small todo manager. Its commands come from the Input box, one per line, just as they would from a keyboard. It uses for await over the lines, so commands are processed strictly in order even if they are asynchronous.

Node.js A todo REPL with commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Important details in this design:

  • A table of commands (commands) replaces a long if/else chain, and Object.hasOwn prevents input such as constructor or toString from reaching inherited methods.
  • Because the input here is not a terminal, the typed commands are not echoed: the output shows each prompt followed directly by the result. Note that output must be passed to createInterface, otherwise prompt() prints nothing. On a real terminal the user's own typing shows up after each prompt.
  • break ends the loop and closes the interface. Lines after exit (the final list in the Input) are never processed.
  • Every command returns a string; the loop prints it. This keeps the logic testable without any stdin at all.

Terminals, history and tab completion

When input is a real terminal (a TTY), readline switches on line editing: arrow keys move the cursor, Up and Down browse the history of earlier lines, and Ctrl+A, Ctrl+E, Ctrl+W work as in a shell. You can customise this. These features need a real terminal, so the snippet below is read-only; try it on your own machine.

NODE
// Read-only: needs an interactive terminal (a TTY)
import readline from 'node:readline';

const commands = ['help', 'list', 'add', 'done', 'remove', 'exit'];

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'todo> ',
  historySize: 200,                       // remember the last 200 lines (default 30)
  removeHistoryDuplicates: true,
  completer(line) {                       // called when the user presses Tab
    const hits = commands.filter((c) => c.startsWith(line));
    return [hits.length ? hits : commands, line];
  },
});

rl.on('SIGINT', () => {                   // Ctrl+C
  rl.question('Really quit? (y/n) ', (answer) => {
    if (answer.toLowerCase() === 'y') rl.close();
    else rl.prompt();
  });
});

Useful facts to know:

  • process.stdin.isTTY is true for a keyboard and undefined for a pipe or file. Use it to decide whether to print prompts and colours, or to refuse interactive questions when the input is redirected.
  • History is kept in memory only. To keep it between sessions, you save and reload the lines yourself.
  • Ctrl+C on a readline interface emits 'SIGINT' on the interface when you have a listener; otherwise the process receives the signal and exits. Ctrl+D (end of input) closes the interface.
  • For passwords, readline echoes every key unless you hide input yourself (set the terminal to raw mode and stop echoing, or use a package). Never ask for secrets in a way that prints them, and never log them (Configuration, Secrets and Environment).
  • Node also ships node:repl, the module behind the node command's own interactive mode, if you want a full JavaScript REPL inside your app. It is also terminal-bound.

Other helpers in node:readline

The module has a few low-level functions that are useful for progress displays on a terminal: readline.clearLine(stream, 0), readline.cursorTo(stream, x), moveCursor and clearScreenDown. They write terminal control sequences (ANSI escape codes) and do nothing useful when output is redirected to a file, so check process.stdout.isTTY before animating a progress bar. A tiny, runnable look at the idea, which prints the sequences as text so you can see them:

Node.js What cursor control really sends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each call just writes a short escape sequence (\u001b[1G moves to column 1, \u001b[2K erases the line, \u001b[1A moves up one line). A terminal interprets them; a file just contains junk, which is why you must check isTTY first.

Good habits for interactive tools

  1. Detect the mode. Check process.stdin.isTTY: prompt people, but read quietly from pipes.
  2. Write results to stdout and messages to stderr. Prompts and diagnostics belong on stderr when the tool's output is meant to be piped on.
  3. Always close the interface (or let the loop end). An open interface keeps the process alive.
  4. Handle end of input. Ctrl+D or a closed pipe is normal, not an error: handle 'close' or the end of the for await loop.
  5. Validate every answer and re-ask, with a limit on attempts. Treat input as untrusted (Web Application Security).
  6. Set exit codes: process.exitCode = 1 for failures so scripts can react.
  7. Keep logic separate from I/O. The todo example's commands table can be unit tested without readline, exactly like the examples in The Built-in Test Runner.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the 'line' event of a readline interface give you?

    readline buffers incoming chunks and emits complete lines, which is its main value over reading process.stdin directly.
  2. 2. What is the cleanest way to process every line of a large file or of piped input in constant memory?

    The interface is an async iterable of lines. It holds one line at a time, so memory use stays flat however large the input is.
  3. 3. Why can sequential rl.question calls fail when the input is piped?

    With a keyboard, answers arrive after the question is asked. A pipe can deliver all lines at once. Use the line iterator or a 'line' listener for input that might be piped.
  4. 4. What happens if you call rl.question after rl.close()?

    A closed interface cannot be used again; create a new one if you need to read more.
  5. 5. How can a program tell whether a real person is typing at a terminal?

    isTTY is true for an interactive terminal and undefined when input is a pipe or file, so tools use it to decide about prompts, colours and cursor control.

Summary

  • process.stdin delivers arbitrary chunks; readline.createInterface({ input }) turns any readable stream into complete lines with 'line' and 'close' events.
  • Prefer for await (const line of rl) for processing input; set crlfDelay: Infinity so \r\n is one line break.
  • readline/promises offers rl.question(), but sequential questions can lose lines on piped input; use a line iterator or a 'line' listener when input may not come from a keyboard.
  • A closed interface cannot be reused (ERR_USE_AFTER_CLOSE); closing is also what lets the process exit.
  • A REPL is setPrompt, prompt and a loop over lines with a table of commands; keep command logic separate from I/O so it is testable.
  • On a TTY you get history, editing, completer and SIGINT handling; check process.stdin.isTTY and process.stdout.isTTY before relying on them.

Next: Building Command-Line Tools