DEV Community

Cover image for How do you take user inputs in Javascript(NodeJs)?
Caspian Grey
Caspian Grey

Posted on

How do you take user inputs in Javascript(NodeJs)?

There are 2 common methods to take inputs from users in javscript(NodeJs):

  1. Using prompt-sync
  2. Using readline

let's learn how to take inputs using prompt-sync.
In Browser we use window.prompt(), which is a default builtin fucntion in browsers. But NodeJs does not have builtin synchronous method to take inputs.

That's why we use external modules like prompt-sync.
Since, prompt-sync is an external library, we first need to install the library in our terminal using package manager. We will use npm package manager here.

To install the package, simply open the terminal in vscode, go to the current file directory, and type npm install prompt-sync.
It will start the installation.

After the installation is complete, it is ready to use in the code.
Now, let's see how to use prompt-sync in the code.

We will write a program which takes input from users and print it on the screen(which means in terminal).

first we will import the module and call the function.

const prompt = require("prompt-sync")();
Enter fullscreen mode Exit fullscreen mode

The () at the end is used to call the function prompt.
Now, we will use the prompt function and get the user inputs by giving a prompt(it tells the user what we need).

We will store the input in variable/constant.

const userInput = prompt("Enter your name:");
Enter fullscreen mode Exit fullscreen mode

Now we will print the input using console.

Enter fullscreen mode Exit fullscreen mode

For example, if the user enters his name as "David".
The output will show in the terminal as

David
Enter fullscreen mode Exit fullscreen mode

Now, let's see the whole code together here:

npm install prompt-sync
Enter fullscreen mode Exit fullscreen mode
const prompt = require("prompt-sync")();
const userInput = prompt("Enter your name:");
console.log(userInput);
Enter fullscreen mode Exit fullscreen mode

This is how you can take inputs from user in NodeJs terminal using prompt-sync. Use this method until next we learn about readline.
readline is a bit confusing for beginner. That's why i avoided explaining it here. Try using prompt-sync, slowly we will learn everything one by one.

(Caspian Grey)

Top comments (0)