You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:50:34