Node.js readline — 命令行交互
创建命令行问答界面,读取用户输入 · 难度:入门 · +15XP
readline 模块
readline 让你在终端中逐行读取用户输入,适合做命令行工具和交互式脚本。
基本用法
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("你叫什么名字?", (name) => {
console.log(你好,${name}!);
rl.close();
});
多轮问答
const questions = ["你的名字?", "你的年龄?", "你的城市?"];
const answers = [];
let i = 0;
function ask() {
if (i >= questions.length) {
console.log("
你的信息:", answers.join(", "));
rl.close();
return;
}
rl.question(questions[i], (ans) => { answers.push(ans); i++; ask(); });
}
ask();