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

使用Bun开发CLI工具:单行stdin读取二次调用失效问题求助

问题原因及修复方案

问题原因

你用for await (const input of console)的方式读取输入,本质是把console当作stdin的异步迭代器使用,但这个迭代器是一次性单例:第一次调用getInput时,迭代器被启动并读取了第一行输入,即便提前用return终止循环,迭代器的内部状态也会被标记为后续无更多输入。第二次调用getInput时,遍历这个已耗尽的迭代器,循环直接不执行,函数会立即返回,自然无法获取新输入。

修复方法

Bun提供了专门的Bun.stdin.readline()方法用于读取单行标准输入,该方法支持多次调用,每次调用都会等待用户输入一行内容后返回。修改后的代码如下:

async function getInput() {
  // 可选:用trim()去除首尾空白和换行符
  return (await Bun.stdin.readline())?.trim();
}

async function liveTest() {
  /* some code here */
  console.log("input1:");
  const input1 = await getInput();
  console.log(`你输入的内容:${input1}`);
  /* some code here */
  console.log("input2:");
  const input2 = await getInput();
  console.log(`你输入的内容:${input2}`);
  /* some code here */
}

liveTest();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:07:16