I am implementing a cli tool using bun. I have to collect inputs from user during runtime and I specifically need only one line from stdin. This is what I have implemented so far by referring the docs:
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();
I am running it using bun file.js
command. I am observing a problem where the input2 is not actually being collected. It just directly moves to the remaining code.
Can someone explain why and provide a fix/workaround?
2
Answers
The problem is that you are restarting a
for await
loop on the same async iterator (console
). This doesn’t work, because even if you exit the loop prematurely, the iterator is told to clean up (itsreturn
method is called). If you don’t intend to do your work in the body of thefor await
loop, then just call.next()
on the async iterator, like this:you can use
then()