Node.js readline Module
Node.js'sreadlinemodule is an interface for reading data line by line from a readable stream (such asprocess.stdin). It provides a simple way to handle command-line input and is very suitable for creating interactive command-line applications.
Basic Usage
Import the readline module
To usereadlinemodule, you first need to import it:
Create a readline interface
Creatingreadline.Interfacean instance is the core of using this module:
Example
input: process.stdin,
output: process.stdout
});
Here we created an interface that reads data from standard input (keyboard) and writes output to standard output (console).
Main Methods and Events
Reading Input Line by Line
Usequestion()method to ask the user a question and wait for an answer:
Example
console.log(`Hello, ${answer}!`);
rl.close();
});
Listening for the line event
When the user enters a line and presses Enter, thelineevent is triggered:
Example
console.log(`Received: ${input}`);
if (input === 'exit') {
rl.close();
}
});
Closing the Interface
Useclose()method to close the interface and release resources:
Example
When the interface is closed, thecloseevent is triggered:
Example
console.log('Goodbye!');
process.exit(0);
});
Advanced Features
History
readlineThe module supports command history functionality:
Example
Users can use the up and down arrow keys to browse historical commands.
Custom Completion
You can implement custom Tab completion functionality:
Example
const completions = ['help', 'exit', 'show'];
const hits = completions.filter((c) => c.startsWith(line));
return [hits.length ? hits : completions, line];
});
Cursor Control
readlineProvides some methods to control the cursor:
Example
readline.clearLine(process.stdout, 0); // Clear the current line
readline.clearScreenDown(process.stdout); // Clear content below the cursor
Practical Application Examples
Create a simple command-line Q&A program
Example
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const questions = [
'What is your name?',
'How old are you this year?',
'What is your favorite programming language?'
];
const answers = [];
function askQuestion(i = 0) {
if (i >= questions.length) {
console.log('Thank you for your answers:', answers);
return rl.close();
}
rl.question(questions[i], (answer) => {
answers.push(answer);
askQuestion(i + 1);
});
}
askQuestion();
Create a simple command-line calculator
Example
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function calculator() {
rl.question('Please enter an expression (e.g., 2 + 3, or type exit to quit): ', (input) => {
if (input === 'exit') {
return rl.close();
}
try {
const result = eval(input); // Note: In real applications, avoid using eval directly
console.log(`Result: ${result}`);
} catch (e) {
console.log('Invalid expression');
}
calculator(); // Recursively call to continue the next calculation
});
}
calculator();
Security Considerations
Avoid using eval(): The calculator example above used
eval(), which is unsafe in production environments because it executes any input JavaScript code. In real applications, you should use a dedicated expression parser.Input validation: Always validate user input to prevent injection attacks or other security issues.
Error handling: Add appropriate error handling for all asynchronous operations.
Summary
Node.js'sreadlinemodule is a powerful tool for building interactive command-line tools. With it, we can:
- Easily get user input
- Create Q&A-style interactive interfaces
- Implement command history
- Add Tab completion functionality
- Control terminal cursor and output
MasterreadlineThe module is an important step in developing Node.js command-line tools. I hope this article helps you understand and use this module.
Node.js Built-in Modules