Getting User Input In Node.js

Node.js allows us to run javascript code outside the browser, thus becoming a great tool to interact with fileSystem, web servers,etc!! In this article, we will show you an easy way to get inputs from user in node.

Using PROMPT-SYNC:

The prompt-sync Node Module provides the simplest way to take inputs from the user!

1)Make Sure you have Node and NPM installed .

2)Run npm install prompt-sync in the terminal.

const input = require('prompt-sync')();

The above line states to import the node module in our project and calling the functionality in the module

Once You have successfully imported the node module. You can now make use of it for taking user-input as follows:

const input = require('prompt-sync')();
const name = prompt('What is your name?');
console.log(`Hello !!!!${name}`);

LETTING USERS EXIT:

Usually in node we use (Ctrl + c) to exit from the program.With prompt-sync, to allow users to exit at their will,we pass an object when the module is called.The modified code then becomes,

const input = require('prompt-sync')({sigint: true});

Working With Numbers:

Make sure that all the input data is primarily string. So in-order to deal with numbers please make sure you are making appropriate type conversion of string into numbers.

This is how we can take inputs from user using a very simple node module !! I hope You get something new to read from this article.

Thanks For Reading :)

No Comments Yet