Node.js – readline Module
Subject: nodejs
Node.js – readline Module
The readline
module in Node.js provides an interface for reading input from a readable stream (such as process.stdin
) one line at a time. It's especially useful for creating interactive command-line tools, user input forms, or CLI utilities that take user input from the terminal.
This module is built into Node.js and does not require external installation.
Why Use the readline Module?
- To accept interactive input from users in the terminal
- To build command-line interfaces (CLI)
- To create tools that need input/output logic line-by-line
- For scripting or processing file streams line by line
Importing the Module
Basic Example – Reading User Input
Output:
How It Works
readline.createInterface()
creates an input/output interface.rl.question()
prompts the user and executes a callback when a response is entered.rl.close()
terminates the interface and releases the stream.
Reading Multiple Lines – Line-by-Line Input
Output:
Handling Close Event
Reading From a File Line by Line
Explanation:
- Useful for reading large files without loading the entire file into memory.
crlfDelay: Infinity
ensures compatibility with all newline characters (\r\n, \n).
Real-World Use Cases
- CLI tools (e.g., interactive menus, scripts)
- Text file processors
- Chatbots or terminal-based games
- Prompt-based forms in terminal environments
Key Takeaways
readline
is a powerful module for handling user input via the command-line.- You can capture single or multiple lines interactively or from a stream.
- Ideal for CLI-based applications, scripts, and input processing tools.
- It is essential for Node.js developers building terminal utilities or tools that require interactive input.