How to use readline-sync In NodeJS
This module is used to receive input from the user synchronously, ensuring program execution line by line.
Installing module:
npm install readline-sync
Project structure:
Example: Implementation to take input array from the user.
// Importing the module
const readline = require("readline-sync");
// Enter the number
let a = Number(readline.question());
let number = [];
for (let i = 0; i < a; ++i) {
number.push(Number(readline.question()));
}
console.log(number);
Step to Run Application: Run the application using the following command from the root directory of the project
node index.js
Output:
Example: Implementation to find the frequency of the numbers
// Importing the module
const readline = require("readline-sync");
// Enter the number
let a = Number(readline.question());
let number = [];
// Creating map
let map = new Map();
for (let i = 0; i < a; ++i) {
let number = Number(readline.question());
if (map.has(number)) {
map.set(number, map.get(number) + 1);
} else {
map.set(number, 1);
}
}
console.log(map);
Step to Run Application: Run the application using the following command from the root directory of the project
node index.js
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
Contact Us