4 Ways to take user input from the terminal in Nodejs.

aman tomar
3 min readAug 31, 2022

When we start learning any programming language, we want to take user input from the terminal. Most people start their programming journey in c, c++, java, etc. In these languages, we have inbuilt functions/classes to take user input from the terminal but if you are starting your programming journey from Javascript then for taking user input the process is somewhat different.
I am sharing 4 ways to take user input from the terminal in Nodejs. The first approach is a native Nodejs approach and the rest approaches will use libraries.

Native Approach

Readline

We have one built-in module Readline for reading of input stream line by line

For user Interaction first, we have to create an interface with the createInterface() method. This method takes two arguments. The first argument will be for the standard input and the second one will be for reading the standard output.

Now the returned object has one method question which expects two parameters a string and a callback function.

But the problem is it will not exit the application. We can give further input.

To exit the application we have to call the close method.

Library Approach

1. Inquirer

We have to install this package in our local to use this. For nodejs install using this command npm install inquirer@^8.0.0

This package provides us a method prompt() to take user input and it expects an array of questions object.

The result will be an object.

2. Prompt-Sync

We have to install this package in our local to use this

We have to use prompt() for taking user Input.

If the user hit enter without answering, we can show the default answer. Prompt expect default answer as the second parameter. this is an optional parameter.

If the user enters the name then the output will be:-

If the user hit enter without any answer

3. Readline Sync

We have to install this package in our local to use this

This is built on top of Readline module.

We have to call the same question method as readline but the interesting part is we don’t have to create the interface and call the close method.

For more details, you can read the documentation.

If you like the content please follow.

Want to connect? Reach out to me on Linkedin

--

--