readline
The readline
module provides an interface for reading input line by line from a readable stream (such as process.stdin
). Supports prompts, history, and question/answer patterns.
API Surface
Interface
readline.createInterface(options)
— create interface.
Options:input
: readable stream (e.g.,process.stdin
)output
: writable stream (e.g.,process.stdout
)prompt
: prompt string
Methods
rl.question(query, cb)
— ask question, call cb with answer.rl.prompt()
— display prompt.rl.close()
— close interface.
Events
'line'
— emitted when user enters a line.'close'
— when input closes.'SIGINT'
— on Ctrl+C.
Examples (English only)
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: "> "
});
rl.prompt();
rl.on("line", (line) => {
console.log("You typed:", line);
if (line === "exit") rl.close();
else rl.prompt();
});
rl.on("close", () => {
console.log("Goodbye!");
process.exit(0);
});
// Ask a single question
// rl.question("What is your name? ", (answer) => {
// console.log("Hello", answer);
// rl.close();
// });
Notes
- Use
question
for simple one-time input. - Use
line
event withprompt
for interactive shells. - Always call
close
when done to free resources. - Handle
SIGINT
(Ctrl+C) if you need graceful shutdown.