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

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.

image.png

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

image.png

image.png

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.

image.png

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

image.png

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

image.png

image.png

The result will be an object.

2. Prompt-Sync

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

image.png

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.

image.png

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

image.png

If the user hit enter without any answer

image.png

3. Readline Sync

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

This is built on top of Readline module.

image.png

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.

image.png

image.png

For more details, you can read the documentation.

If you like the content please follow.

Did you find this article valuable?

Support Aman Singh Tomar by becoming a sponsor. Any amount is appreciated!