乐闻世界logo
搜索文章和话题

How can I read a single line user input with Bun.js?

1个答案

1

Bun.js is a relatively new JavaScript runtime environment, similar to Node.js, but designed to provide higher performance and a better developer experience. Reading a single line of user input in Bun.js can be achieved in multiple ways, but the most common approach is to use the built-in stdin method. Here is a step-by-step guide along with example code:

  1. Import necessary modules – Bun.js provides the built-in stdin method for reading data from standard input.
  2. Create a function to read input – Use the stdin.read method to obtain input. As it is asynchronous, the await keyword is required.
  3. Process the input – After reading the input, you can further process or use the data as needed.

Example code:

javascript
// Import Bun's built-in module const { stdin } = Bun; async function readSingleLineInput() { // Prompt user for input console.log("Enter your data:"); // Read a line of input let userInput = await stdin.read(); // Handle possible newline characters userInput = userInput.trim(); // Output or process user input console.log("Your input is:", userInput); return userInput; } // Call the function readSingleLineInput();

Code explanation:

  • The stdin.read() method reads user input until a newline character (when Enter is pressed) is encountered.
  • The trim() method removes whitespace characters (including newline characters) from both ends of the string, which is particularly useful when handling command-line input.
  • This function is asynchronous and returns the user input content.

This approach makes reading a single line of user input in the Bun.js environment simple and efficient. In actual development, this can be applied to receiving configuration options, user feedback, or other scenarios requiring command-line interaction with users.

2024年7月26日 22:04 回复

你的答案