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:
- Import necessary modules – Bun.js provides the built-in
stdinmethod for reading data from standard input. - Create a function to read input – Use the
stdin.readmethod to obtain input. As it is asynchronous, theawaitkeyword is required. - 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 回复