The Readline Module in Node.js

The readline module in Node.js provides an interface for reading data from a Readable stream (such as process.stdin) line by line. It is widely used for building command-line interfaces (CLIs), handling user input, and processing files line-by-line. Node.js supports both Promise-based APIs and Callback-based APIs for working with readline.

readline.Interface / readlinePromises.Interfaceline, close, pause, resume, SIGINT, SIGTSTPrl.question()rl.prompt(), rl.setPrompt(), rl.getPrompt()rl.write(), rl.cursorTo(), rl.moveCursor()

~2 min read • Updated Dec 30, 2025

1. Introduction


The readline module allows developers to read input line by line from streams. It can be loaded with require('node:readline') or the Promise-based version require('node:readline/promises').


2. Creating an Interface


const readline = require('node:readline');
const { stdin: input, stdout: output } = require('node:process');
const rl = readline.createInterface({ input, output });

3. Key Events


  • line: Triggered when a line of input is received.
  • close: Triggered when the interface is closed.
  • pause / resume: Manage input stream state.
  • SIGINT: Triggered by Ctrl+C.
  • SIGTSTP / SIGCONT: Handle backgrounding and resuming processes.
  • history: Triggered when the input history changes.

4. Core Methods


  • rl.question(query, callback): Displays a query and captures user input.
  • rl.prompt(): Displays the prompt and waits for input.
  • rl.setPrompt(prompt): Sets the prompt text.
  • rl.getPrompt(): Returns the current prompt.
  • rl.write(data[, key]): Writes data or simulates key input.
  • rl.close(): Closes the interface.

5. Async Iteration


The readline interface supports for await...of loops for asynchronous line-by-line processing:


for await (const line of rl) {
  console.log(`Received: ${line}`);
}

6. Example Use Cases


  • Simple CLI: Build interactive command-line tools with custom commands.
  • File Processing: Read files line-by-line using fs.createReadStream() with readline.

7. TTY Keybindings


The readline module supports keybindings such as Ctrl+C, Ctrl+D, Ctrl+U, and Ctrl+K for managing input in terminal sessions.


Conclusion


The readline module is a powerful tool for building interactive applications in Node.js. With support for both Promise-based and Callback-based APIs, rich event handling, and file processing capabilities, it is essential for developing CLIs and data-processing utilities.


Written & researched by Dr. Shahin Siami