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

JavaScript猜数字游戏出现ERR_MODULE_NOT_FOUND错误求助

问题排查与修复方案

核心问题分析

  1. 错误根源:colorama是Python生态的终端颜色工具,Node.js环境下无法直接导入使用,这是你遇到ERR_MODULE_NOT_FOUND的直接原因。
  2. 其他问题:
    • Node.js没有全局的input()函数,无法直接获取用户输入
    • 依赖第三方random库增加了入门项目的复杂度,其实可以用内置API实现随机数生成

修复后的代码(无需第三方依赖)

// 使用ANSI转义序列实现终端文字颜色,无需安装任何包
const COLORS = {
  MAGENTA: '\x1b[35m',
  RED: '\x1b[31m',
  GREEN: '\x1b[32m',
  YELLOW: '\x1b[33m',
  RESET: '\x1b[0m' // 重置颜色,避免后续终端文字一直变色
};

// 使用Node.js内置readline模块处理用户输入
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

// 生成1-35之间的随机数(Math.random()返回0-1的浮点数,处理后得到整数)
const secretNumber = Math.floor(Math.random() * 35) + 1;
let chances = 1;

console.log(`${COLORS.MAGENTA}Guess the randomly generated number from 1 to 35${COLORS.RESET}`);

// 封装用户输入的递归函数,实现循环猜数
function askGuess() {
  readline.question('Guess a number between 1 and 35: ', (input) => {
    const guess = parseInt(input, 10);

    // 验证输入是否为有效数字
    if (isNaN(guess)) {
      console.log('Please enter a valid number!');
      askGuess();
      return;
    }

    if (guess > 35 || guess < 1) {
      console.log('Sorry, that number is outside the 1-35 range!');
      askGuess();
      return;
    }

    if (guess > secretNumber) {
      console.log(`${COLORS.RED}Guess Lower!${COLORS.RESET}`);
      chances++;
      askGuess();
    } else if (guess < secretNumber) {
      console.log(`${COLORS.GREEN}Guess Higher!${COLORS.RESET}`);
      chances++;
      askGuess();
    } else {
      console.log(`${COLORS.YELLOW}Hurray! You got it in ${chances} tries, the number was ${secretNumber}${COLORS.RESET}`);
      readline.close(); // 结束输入会话
    }
  });
}

// 启动游戏
askGuess();

关键修复说明

  • 颜色处理:用ANSI转义序列替代Python的colorama,无需额外安装依赖,直接在Node.js终端生效
  • 用户输入:使用Node.js内置的readline模块实现交互式输入,这是Node.js获取终端输入的标准方式
  • 随机数生成:用内置Math.random()替代第三方random库,减少项目依赖更适合入门
  • 输入验证:新增了非数字输入、超出范围输入的处理,提升游戏健壮性

内容的提问来源于stack exchange,提问作者Arnav Chetan Yadwadkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:35:39