How to use Reading from Standard Input (stdin) In NodeJS
Reading from standard input (stdin) allows your Node.js application to receive input directly from the user via the command line. You can use the process.stdin
stream to read input from the command line asynchronously.
process.stdin.on('data', (data) => {
console.log(`You entered: ${data.toString().trim()}`);
});
Example: Implementation to take input using stdin method.
process.stdout.write('Enter your name: ');
process.stdin.on('data', (data) => {
const name = data.toString().trim();
console.log(`Hello, ${name}!`);
process.exit(); // Exit the process after receiving input
});
Output:
How to Take Input in Node.js ?
Taking input in a Node.js application is essential for building interactive command-line interfaces, processing user input, and creating dynamic applications. Node.js provides several methods for receiving input from users, including reading from standard input (stdin), command-line arguments, and user prompts. This article will cover various techniques for taking input in Node.js, along with examples and best practices.
Table of Content
- Using readline-sync
- Using Reading from Standard Input (stdin)
- Conclusion