Giving Input to a Node.js Application


The main aim of a Node.js application is to work as a backend technology and serve requests and return response. But we can also pass inputs directly to a Node.js application.

We can use readline-sync, a third-party module to accept user inputs in a synchronous manner.

Syntax

npm install readline-sync

This will install the readline-sync module dependency in your local npm project.

Example 1

Create a file with the name "input.js" and copy the following code snippet. After creating the file, use the command "node input.js" to run this code.

//Giving Input to a Node.js application Demo Example

// Importing the realine-sync module
const readline = require("readline-sync");

console.log("Enter input : ")
// Taking a number input
let num = Number(readline.question());
let number = [];
for (let i = 0; i < num; i++) {
      number.push(Number(readline.question()));
}
console.log(number);

Output

C:\home
ode>> node input.js Enter input: 5 1 2 3 4 5 [ 1, 2, 3, 4, 5 ]

Example 2

Let’s have a look at one more example

//Giving Input to a Node.js application Demo Example

// Importing the realine-sync module
const readline = require("readline-sync");

// Enter the number
console.log("Enter the number :")
let num = Number(readline.question());
let number = [];

// Creating map
let map = new Map();
for (let i = 0; i < num; 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);

Output

C:\home
ode>> node input.js Enter the number : 4 21 12 786 987 Map { 21 => 1, 12 => 1, 786 => 1, 987 => 1 }

Updated on: 18-Aug-2021

528 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements