Bun.js: Read a single line user input

48 Views Asked by At

Bun.js has a useful 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);
}

Is there a way to read user inputs, outside a loop?


I found this solution:

const stdinIterator = process.stdin.iterator()

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

console.write(`What would you like, ${userName}?\n> `)
const answer = (await stdinIterator.next()).value.toString().trimEnd()
console.log('Do something with answer:', answer)

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

0

There are 0 best solutions below