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.

Javascript
// 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

Javascript
// 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

Similar Reads

Using readline-sync

This module is used to receive input from the user synchronously, ensuring program execution line by line....

Using Reading from Standard Input (stdin)

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....

Conclusion

Taking input in Node.js is crucial for building interactive and user-friendly applications. Whether you need to read input from standard input, command-line arguments, or user prompts, Node.js provides various methods and libraries to accommodate different use cases. By understanding these techniques and implementing them effectively, you can create powerful and dynamic Node.js applications that cater to user input seamlessly....