Nodejs Readline Module
[Node.js Built-in Modules](#)
* * *
The `readline` module in Node.js is an interface for reading data line by line from readable streams (such as `process.stdin`). It provides a simple way to handle command line input, making it perfect for creating interactive command line applications.
* * *
## Basic Usage
### Importing the readline Module
To use the `readline` module, you first need to import it:
const readline = require('readline');
### Creating a readline Interface
Creating a `readline.Interface` instance is the core of using this module:
## Example
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
Here we create an interface that will read data from standard input (keyboard) and write output to standard output (console).
* * *
## Main Methods and Events
### Reading Input Line by Line
You can use the `question()` method to ask the user a question and wait for an answer:
## Example
rl.question('What is your name?',(answer)=>{
console.log(`Hello, ${answer}!`);
rl.close();
});
### Listening for the line Event
When the user enters a line of content and presses Enter, the `line` event is triggered:
## Example
rl.on('line',(input)=>{
console.log(`Received: ${input}`);
if(input ==='exit'){
rl.close();
}
});
### Closing the Interface
Use the `close()` method to close the interface and free up resources:
## Example
rl.close();
When the interface is closed, the `close` event is triggered:
## Example
rl.on('close',()=>{
console.log('Goodbye!');
process.exit(0);
});
* * *
## Advanced Features
### History
The `readline` module supports command history:
## Example
rl.history=['command1','command2'];// Set history
Users can use the up and down arrow keys to browse through historical commands.
### Custom Completion
You can implement custom Tab completion:
## Example
rl.on('completer',(line)=>{
const completions =['help','exit','show'];
const hits = completions.filter((c)=> c.startsWith(line));
return[hits.length? hits : completions, line];
});
### Cursor Control
`readline` provides some methods to control the cursor:
## Example
readline.cursorTo(process.stdout,10,5);// Move cursor to column 10, row 5
readline.clearLine(process.stdout,0);// Clear the current line
readline.clearScreenDown(process.stdout);// Clear content below the cursor
* * *
## Practical Application Examples
### Creating a Simple Command Line Q&A Program
## Example
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const questions =[
'What is your name?',
'How old are you?',
'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,(answer)=>{
answers.push(answer);
askQuestion(i +1);
});
}
askQuestion();
### Creating a Simple Command Line Calculator
## Example
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function calculator(){
rl.question('Please enter an expression (e.g., 2 + 3 or enter exit to quit): ',(input)=>{
if(input ==='exit'){
return rl.close();
}
try{
const result = eval(input);// Note: avoid using eval directly in production
console.log(`Result: ${result}`);
}catch(e){
console.log('Invalid expression');
}
calculator();// Recursive call to continue next calculation
});
}
calculator();
* * *
## Security Considerations
1. **Avoid using eval()**: The calculator example above uses `eval()`, which is unsafe in production environments because it executes any input JavaScript code. In real applications, you should use a dedicated expression parser.
2. **Input Validation**: Always validate user input to prevent injection attacks or other security issues.
3. **Error Handling**: Add proper error handling for all asynchronous operations.
* * *
## Summary
The `readline` module in Node.js is a powerful tool for building interactive command line applications. Through 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
Mastering the `readline` 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](#)
YouTip