6

Bun.js has a nice native API to read periodical user input:

const prompt = "Type something: ";
process.stdout.write(prompt);
for await (const line of console) {
  console.log(`You typed: ${line}`);
  process.stdout.write(prompt);
}

But...

I want to read user inputs, outside a loop!


I found this solution:

const stdinIterator = process.stdin.iterator()

console.write('What is your first name?\n> ')
const firstName = (await stdinIterator.next()).value.toString().trimEnd()
console.log('Hello,', firstName)

console.write('What is your last name?\n> ')
const lastName = (await stdinIterator.next()).value.toString().trimEnd()
console.log('Welcome', `${firstName} ${lastName}`)

It works. But then the process is not terminated automatically (I need to press Ctrl+C manually).

2
  • Just add a break; at the end of the loop. Commented Mar 30, 2024 at 12:48
  • 2
    Directly accessing the console iterator is broken. github.com/oven-sh/bun/issues/7541 Commented Mar 30, 2024 at 12:49

2 Answers 2

6

Bun.js has implemented prompt API.

Use it and enjoy:

const firstName = prompt('What is your first name?')
console.log('Hello,', firstName)

const lastName = prompt('What is your last name?')
console.log('Welcome', `${firstName} ${lastName}`)

See: https://bun.sh/docs/api/globals

Sign up to request clarification or add additional context in comments.

Comments

1

From a comment posted by aboqasem on 2024-03-31 it's possible to close the iterator by invoking the return() method:

const iterator = console[Symbol.asyncIterator]();
const text = (await iterator.next()).value;

await iterator.return?.();

I've successfully used this in my project running Bun v1.1.17.

And because the stream is closed it allows the process to end normally without needing to ctrl + c to end it.

1 Comment

Thanks, also not to skip process.stdout.write(prompt);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.