Understanding the Readline Module
The readline module in Node.js is designed to read data from a readable stream, such as process.stdin, one line at a time. It’s especially handy for creating command-line interfaces (CLIs) or reading large files without loading them entirely into memory.
Key Features
- Line-by-Line Reading: Efficiently process data one line at a time.
- Event-Driven: Leverages Node.js’s event-driven architecture.
- Customizable Interfaces: Allows for tailored input and output streams.
Before diving into the example, ensure you have Node.js installed. You can check this by running node -v
in your terminal. If you don’t have Node.js installed, download it from the official Node.js website.
Example: Building a CLI quiz app
In this example, we’ll create a simple CLI quiz application using the readline
module. This app will ask users a series of questions and provide immediate feedback.
Step 1: Initialize the readline interface
First, import the readline
module and set up the interface.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
Step 2: Define the questions and logic
Let’s define a few quiz questions and the logic to process user responses.
const questions = [
{ query: "What is 2 + 2?", answer: "4" },
{ query: "Name the largest planet in our solar system.", answer: "Jupiter" },
// Add more questions as needed
];
let currentQuestion = 0;
function askQuestion() {
rl.question(questions[currentQuestion].query + ' ', (userInput) => {
if (userInput.trim() === questions[currentQuestion].answer) {
console.log("Correct!");
} else {
console.log("Incorrect. The correct answer is:", questions[currentQuestion].answer);
}
currentQuestion++;
if (currentQuestion < questions.length) {
askQuestion();
} else {
rl.close();
}
});
}
Step 3: Start the quiz
Finally, kick off the quiz by calling askQuestion()
.
askQuestion();
Step 4: Testing the application
Run your Node.js application by navigating to the directory containing your script and running node <script-name>.js
. Answer the questions to see how the application responds.