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

Node.js readline模块异常:无法进入后续逻辑,控制台无响应

问题原因

你代码里的核心问题是**rl.question()本身不返回Promise**,直接用await调用它会导致Promise永远处于pending状态,程序彻底卡住,所以控制台失去响应。

修复方案

把rl.question()包装成返回Promise的函数,这样就能正常用async/await处理异步输入了。修改后的完整代码如下:

const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

// 把question方法包装成Promise
function askQuestion(prompt) {
  return new Promise(resolve => {
    rl.question(prompt, resolve);
  });
}

async function clientOpener() {
  const startGame = await askQuestion(`Choose a number:
1)Start a bowling game
2)Exit simulation
`);
  
  const y = "1";
  const n = "2";
  
  if (y === startGame) {
    const playerCount = await askQuestion("Ok how many players will there be (MAX: 8 players)\n");
    const parsedInput = parseInt(playerCount);
    
    if (parsedInput > 0 && parsedInput <= 8) {
      let listOfNames = [];
      for (let i=0; i<parsedInput; i++) {
        const name = await askQuestion(`Enter name #${i}\n`);
        listOfNames.push(name);
        console.log(`Added ${name} to list of players\n`);
      }
      console.log(listOfNames);
    }
    rl.close();
  } else if (n === startGame) {
    console.log("Ending interface");
    rl.close();
  } else {
    console.log("Please enter a valid option");
    clientOpener();
  }
}

clientOpener();
关键修改点
  • 新增askQuestion函数,将rl.question的回调逻辑转换为Promise,让await能正常等待用户输入
  • 把clientOpener改为async函数,直接用await调用包装后的提问函数,避免嵌套回调和无效的await
  • 统一处理提示信息的换行,保证输出格式清晰

内容的提问来源于stack exchange,提问作者macman926

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:00:42