Node.js Readline Module
Node.js Readline Module
The Readline module allows Node.js to read input from a readable stream, such as:
-
The terminal (stdin)
-
A file stream
It is mainly used to create command-line interfaces (CLI) where you take input from the user.
This module is built-in, so no installation is required.
✔️ Importing the Readline Module
CommonJS
ES Module
✅ Creating a Readline Interface
rl is now your input/output interface.
📌 1. rl.question() — Ask a Question
📌 2. rl.on(‘line’) — Event for Every Line Entered
You can close it manually:
📌 3. rl.on(‘close’) — Triggered When Interface Closes
📌 4. Readline with Promises (Modern Usage)
(From Node.js v17+)
📌 5. Reading a File Line-by-Line
📌 6. rl.write() — Output Text Manually
📌 7. rl.setPrompt() & rl.prompt()
📌 8. rl.history — User Command History
⭐ Complete Example: Command-Line Calculator
⭐ Summary Table
| Method / Event | Description |
|---|---|
createInterface() |
Creates input/output interface |
question() |
Ask user a question |
on('line') |
Trigger on each line input |
on('close') |
Trigger when closed |
setPrompt() |
Set command prompt text |
prompt() |
Display prompt |
write() |
Write output manually |
.promises.question() |
Promise-based question |
