Node.js Readline Module: Working with User Input

Have you used “npm init” in your projects? If you run it without the “-y” flag, it asks for multiple inputs to create a configuration file package-log.json. Have you wondered how you can create this functionality for your CLI-based application so that it can take user input and provide the related response? Here comes Readline, a super useful Node.js library.

Introduction to Node.js Readline

The Readline Module is a built-in module in Node.js used for handling user inputs and providing resultant output to the command line. This module implements the process input stream and output stream to give the functionality of reading input and writing output. 

Importing Syntax

Since the Readline is a built-in Node.js module, we don’t have to install it, however, importing it is necessary.

Following is the syntax to import the Readline Module in your projects:

const readline = require('readline');

Let us now look at a simple example.

Example of Readline Module

Let’s write some simple JavaScript code to create a program using the Readline interface to receive a name as input and then log a message “Hello” concatenated with the entered value. 

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.question('What is your name? ', (name) => {
    console.log('Hello ' + name);
    rl.close();
});

Here we first import the module, then create a readline interface using the createInterface method and pass process stdin and stdout for read and write to the console. We use this rl object to show a message to prompt user input and inside its callback print the results to the console. Finally, as an additional step, we close the rl interface to clear the resources taken by it.

Output:

Readline Module Example

You can find more information about process.stdin and process.stdout in the “Node Process Object” tutorial.

Method of Node.js Readline Module

Beyond the basics of reading and writing to the terminal, Readline also offers some other useful methods to enhance the user experience. Let’s understand their use case, syntax and examples one by one.

1. createInterface()

This method creates an instance of the InterfaceConstructor class. This method takes process.stdin and process.stdout as arguments to create the instance. This instance is associated with a single input stream for reading and an output stream for writing.

Syntax:

readline.createInterface(input, output);

Example:

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

2. rl.question()

This method is used to take input from the user. This method takes two arguments, a question to ask from the user and a callback function. This callback is used to get the entered value.

Syntax:

rl.question(message, callback);

Example:

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.question('What is your name? ', (name) => {
    console.log('Hello ' + name);
});

Output:

rl.question Example Output

In the output, you can notice that the application keeps asking for input even after entering an input, for getting rid of this we have another method rl.close().

3. rl.close()

This method is used to close the Interface i.e. take control of the input and output stream from the instance of InterfaceConstructor.

Syntax:

rl.close()

Example:

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.question('What is your name? ', (name) => {
    console.log('Hello ' + name);
    rl.close();
});

Output:

rl.close Example Output

Note: This method does not immediately stop the other event to happens like ‘line’, ‘close’, ‘resume’, etc.

4. rl.resume()

This method resumes the input streams if it is paused but it doesn’t prompt anything.

Syntax:

rl.resume()

Example:

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.question('What is your name? ', (name) => {
    console.log('Hello ' + name);
    rl.close();
    rl.resume();
});

Output:

rl.question Example Output

5. rl.setPrompt()

This method is used to set prompts. It takes a string containing any kind of message as an argument.

Syntax:

rl.setPrompt(message)

Example:

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('Enter your name: ');

6. rl.prompt()

This method is used to output the value set by rl.setPrompt() in the new line in the console. It resumes the input stream if it is paused and provides a new location for the user to enter the input.

Syntax:

rl.prompt()

Example:

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('Enter your name: ');

rl.prompt();

Output:

rl.prompt Example Output

To get the entered input, we have to use another method rl.on().

7. rl.on()

This method takes an event and a callback to return the output. The event can be “line” which will activate when the enter key is pressed, “pause” which is active when input steam is paused, “resume” when it resumes, “SIGINT” when the user presses ctrl + c, and “SIGTSTP” when user press ctrl + z. 

Syntax:

rl.on(event, callback)

Example:

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('Enter your name: ');

rl.prompt();

rl.on('line', (line) => {
  console.log(`Hello ${line}`);
  rl.close();
});

Output:

rl.on Example Output

Summary

In this tutorial, we learned to use the Readline module in NodeJS. The Readline module is used for reading input and writing output to the console. It provides a way to prompt different types of messages while giving the option to enter the input. It helps in performing question-answer types operations. If you want to try this module yourself, you can create a calculator application using all of the above methods.

Read More: Asynchronous Programming in Node.js – Callback, Promises & Async Await

Reference

https://nodejs.org/api/readline.html

Aditya Gupta
Aditya Gupta
Articles: 109