Node.js ESM环境下如何获取用户输入?RPG CLI开发遇阻
解决Node.js ESM环境下CLI游戏的输入问题
一、修复readline代码问题
你的readline代码核心问题是没有处理question的回调逻辑,且提前关闭了输入接口,导致用户还没输入程序就终止了。修正后的代码如下:
import readline from "readline"; import { stdin as input, stdout as output } from "node:process"; const run = () => { console.clear(); console.log(` +-----------------------------+ | Welcome ! | +-----------------------------+ `); console.log(` 1. Start game 👍 2. Load game 💾 3. Exit ❌ `); const rl = readline.createInterface({ input, output }); rl.question("Your choice (1-3): ", (answer) => { switch(answer.trim()) { case "1": console.log("Starting new game..."); // 此处添加开始游戏的逻辑 break; case "2": console.log("Loading saved game..."); // 此处添加加载游戏的逻辑 break; case "3": console.log("Exiting game..."); break; default: console.log("Invalid choice, please enter 1-3"); run(); // 重新显示菜单 } rl.close(); // 在回调内关闭接口,确保用户输入完成 }); }; export default run;
关键修正点:
- 给
rl.question添加回调函数,用于接收并处理用户输入 - 将
rl.close()移至回调内部,避免提前关闭输入流 - 添加输入验证和对应逻辑分支
二、Inquirer.js的ESM正确用法
如果想用Inquirer,确保安装支持ESM的版本(v9及以上),执行安装命令:
npm install inquirer@latest
使用正确的ESM导入方式,示例代码:
import inquirer from "inquirer"; const run = async () => { console.clear(); console.log(` +-----------------------------+ | Welcome ! | +-----------------------------+ `); const { choice } = await inquirer.prompt([ { type: "list", name: "choice", message: "Select an option:", choices: [ { name: "Start game 👍", value: "start" }, { name: "Load game 💾", value: "load" }, { name: "Exit ❌", value: "exit" } ] } ]); switch(choice) { case "start": console.log("Starting new game..."); // 开始游戏逻辑 break; case "load": console.log("Loading saved game..."); // 加载游戏逻辑 break; case "exit": console.log("Exiting game..."); process.exit(0); } }; export default run;
注意事项:
- Inquirer的API是异步的,需用
async/await处理 - 确保
package.json中已设置"type": "module",无需额外配置
内容的提问来源于stack exchange,提问作者TheVS
相关产品推荐
相关产品推荐

