bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Core Modules
Node.js•Core Modules

Node.js Readline Module

Introduction to the Readline Module

The Readline module is a core Node.js module that provides an interface for reading data from a Readable stream (like process.stdin ) one line at a time.

It's particularly useful for:

Common Use Cases

Interactive command-line applications

Configuration wizards and setup tools

Command-line games

Formula

REPL (Read - Eval - Print Loop) environments

Processing large text files line by line

Building custom shells and CLIs

Key Features

Line-by-line input processing

Customizable prompts and formatting

Tab completion support

History management

Event-driven interface

Promise-based API support

Note:

The Readline module is built into Node.js, so no additional installation is required. It's perfect for any application that needs to interact with users through the command line or process text input in a line-oriented way.

Getting Started with Readline

Formula

Here's a quick example of using the Readline module to create a simple interactive command - line application:
Basic Interactive Prompt const readline = require('readline');
// Create interface for input/output const rl = readline.createInterface({

input: process.stdin, output: process.stdout

});
// Ask a question and handle the response rl.question('What is your name? ', (name) => {
console.log(`Hello, ${name}!`);
// Ask follow-up question rl.question('How old are you? ', (age) => {
console.log(`In 5 years, you'll be ${parseInt(age) + 5} years old.`);
// Close the interface when done rl.close();
});
});
// Handle application exit rl.on('close', () => {
console.log('Goodbye!');
process.exit(0);
});

Importing and Setup

The Readline module can be imported in several ways depending on your module system and needs: CommonJS (Node.js default)

// Basic require const readline = require('readline');
// Import specific methods using destructuring const { createInterface } = require('readline');
// Create interface with default settings const rl = createInterface({

input: process.stdin, output: process.stdout

});
ES Modules (Node.js 12+)
// Using default import import readline from 'readline';
// Using named imports import { createInterface } from 'readline';
// Dynamic import (Node.js 14+)
const { createInterface } = await import('readline');
// Create interface const rl = createInterface({

input: process.stdin, output: process.stdout

});

Best Practice:

Always close the readline interface using rl.close() when you're done with it to free up system resources and allow your program to exit cleanly.

Creating a Readline Interface

The createInterface method is the main way to create a readline interface. It takes an options object with several configuration properties:

Basic Interface Creation const readline = require('readline');
// Create a basic interface const rl = readline.createInterface({
input: process.stdin,    // Readable stream to listen to output: process.stdout,   // Writable stream to write to prompt: '> ',             // Prompt to display (default: '> ')
});

Common Options:

input : The Readable stream to listen to (default: process.stdin )

output

: The Writable stream to write to (default: process.stdout ) prompt : The prompt string to use (default: '> ') terminal : If true, treats the output as a TTY (default: output.isTTY ) historySize : Maximum number of history entries (default: 30) removeHistoryDuplicates : If true, removes duplicate history entries (default: false) completer

Formula

: Optional function for tab auto - completion crlfDelay

: Delay between CR and LF (default: 100ms) escapeCodeTimeout : Time to wait for character escape sequences (default: 500ms)

Advanced Interface Example

const readline = require('readline');
const fs = require('fs');
// Create an interface with advanced options const rl = readline.createInterface({
input: fs.createReadStream('input.txt'),  // Read from file output: process.stdout,                  // Write to console terminal: false,                         // Input is not a terminal historySize: 100,                        // Larger history removeHistoryDuplicates: true,           // Don't store duplicate commands prompt: 'CLI> ',                         // Custom prompt crlfDelay: Infinity,                     // Handle all CR/LF as single line break escapeCodeTimeout: 200                   // Faster escape code detection
});
// Handle each line from the file rl.on('line', (line) => {
console.log(`Processing: ${line}`);
});
// Handle end of file rl.on('close', () => {
console.log('Finished processing file');
});

Note:

When creating interfaces for file processing, set terminal: false to disable TTY-specific features and improve performance.

Previous

Node.js Util Module