oven-sh/bun

Calling `next` on `console`'s asyncIterable causes its stream to become locked

Open

#7,541 opened on Dec 8, 2023

View on GitHub
 (5 comments) (4 reactions) (1 assignee)Rust (4,486 forks)batch import
buggood first issue

Repository metrics

Stars
 (90,348 stars)
PR merge metrics
 (Avg merge 1d 17h) (357 merged PRs in 30d)

Description

I need to read the first line from stdin, perform some logic, and then iterate over the remaining lines of stdin. The suggested way from the docs (https://bun.sh/docs/api/console) to iterate over stdin lines is using its asyncIterator. But there's no suggested method to get a single line.

I attempted to call the asyncIterator method directly:

let firstLine = (await console[Symbol.asyncIterator]().next()).value;
// perform logic on firstLine
for await (const line of console) {
  // perform logic on remaining lines
}

Defining firstLine this way works. However it will fail on const line of console with the error ReadableStream is locked It seems that manually retrieving an item from console's asyncIterator causes its stream to become locked, and I'm unsure how to unlock it.

I tried using the prompt function with an empty string as the message. But it seems prompt will still print a single space character to stdout if called with an empty string as the message. So it's not ideal.

The best working solution I have right now is to write a for loop that I break out of after one iteration.

for await (const line of console) {
  // perform logic on first line
  break;
}
for await (const line of console) {
  // perform logic on remaining lines
}

I'd appreciate any suggestions on how to unlock the ReadableStream, or how to more elegantly handle this use case.

Originally reported on Discord: Calling nextonconsole's asyncIterable causes its stream to become locked

Contributor guide