Bun 标准输入仅一行

问题描述 投票:0回答:1

我正在使用bun实现一个cli工具。我必须在运行时收集用户的输入,并且我特别需要来自标准输入的一行。这是我到目前为止通过参考文档实现的:

async function getInput() {
  for await (const input of console) {
    return input;
  }
}

async function liveTest() {
  /* some code here */
  console.log("input1:");
  await getInput();
  /* some code here */
  console.log("input2:");
  await getInput();
  /* some code here */
}

liveTest();

我正在使用

bun file.js
命令运行它。我观察到一个问题,即 input2 实际上并未被收集。它只是直接移动到剩余的代码。

有人可以解释原因并提供修复/解决方法吗?

javascript command-line-interface bun
1个回答
0
投票

问题是您正在同一个异步迭代器 (

for await
) 上重新启动
console
循环。这是行不通的。如果您不打算在
for await
循环体中完成工作,则只需在异步迭代器上调用
.next()
即可,如下所示:

async function liveTest() {
  /* some code here */
  console.log("input1:");
  let input = await console.next();
  /* some code here */
  console.log("input2:");
  input = await console.next();
  /* some code here */
}

liveTest();
© www.soinside.com 2019 - 2024. All rights reserved.