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

JavaScript中require('readLine')报错求助:无法输入及无输出问题

Node.js readline 模块使用问题解决

问题根源分析

  1. 模块名拼写错误:你写的require('readLine')中模块名用了大写L,Node.js内置的读取行模块实际是全小写的readline,这就是编辑器下方出现错误标记的直接原因。
  2. 代码逻辑缺失:如果没有正确初始化readline交互接口,程序无法监听终端输入,自然不会有输出也无法输入内容。

正确代码示例

const readline = require('readline');

// 初始化交互接口,关联标准输入输出
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 发起输入提问
rl.question('请输入任意内容:', (inputContent) => {
  console.log(`你输入的内容:${inputContent}`);
  // 必须关闭接口,否则程序会一直挂起
  rl.close();
});

// 监听接口关闭事件,确保程序正常退出
rl.on('close', () => {
  console.log('交互结束');
  process.exit(0);
});

额外检查项

  • 运行代码时,确保是在终端中执行node your-file.js命令,而非编辑器的非交互式环境。
  • 执行node -v确认Node.js环境正常,readline是内置模块,无需额外安装。
  • 检查代码中是否遗漏了接口创建或交互方法调用,这会导致程序无交互逻辑,没有输出。

内容的提问来源于stack exchange,提问作者TEC_Abode of Learning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:35:20