Skip to main content

One post tagged with "Terminal input for js"

View All Tags

· 2 min read

In JavaScript, to take input from the terminal (also known as command line or console input), you can use the built-in "process" object in Node.js. The "process" object provides the "stdin" and "stdout" streams that allow you to read input from the terminal and write output to the terminal, respectively. Here's an example of how you can take input from the terminal in JavaScript using the "process.stdin" stream:

main.js
// Listen for 'data' event on 'stdin' stream
process.stdin.on('data', (data) => {
// Data is a Buffer, so convert it to a string
// trim leading/trailing whitespace
const input = data.toString().trim();

// Process the input
console.log(`You entered: ${input}`);

// Exit the process
process.exit();
});

// Write a prompt to the terminal
console.log("Enter some input: ");

In the example above, the "process.stdin.on('data', ...)" event listener listens for the 'data' event on the 'stdin' stream, which is triggered when the user enters input in the terminal. The input is then processed inside the event handler, and the process is exited using "process.exit()" after processing the input.

You can run this code using Node.js, which is a JavaScript runtime built on the V8 JavaScript engine, specifically designed for server-side development. To run the code, save it to a file with a .js extension, and then execute it using the "node" command in the terminal:

node main.js

Replace "main.js" with the name of the file where you've saved your JavaScript code.