The Readline module provides a way of reading a data stream one line at a time. It is most commonly used to build interactive Command Line Interface (CLI) tools, where you need to ask the user a question and wait for them to type an answer in the terminal.
To use the module, you must create a readline "interface" by linking a readable stream (the user's keyboard input) with a writable stream (the terminal output).
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
Once the interface is set up, you can use rl.question() to display a prompt and wait for user input.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What is your favorite programming language? ', (answer) => {
console.log(Oh, ${answer} is a fantastic choice!);
// You must close the interface, otherwise the script will hang forever!
rl.close();
});
If you copy the code above into a file named prompt.js and run node prompt.js, the terminal will pause, wait for you to type your answer, hit enter, and then respond.
Why must you call `rl.close()` after you are done receiving user input?