Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

nodejs

What is readline module createInterface() in Node.js?

Sarvech Qadir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

We can use the Readline module for a line-by-line reading of any input stream. The module can be made available as follows:

var readline = require('readline');

The Readline module comes with several methods to interact with users. The process is very simple. In order to interact with any user, we must first create an interface initializing input and output stream.

Syntax

readline.createInterface(input, output, completer) 

To create an interface:

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

The method createInterface() takes two parameters – the input stream and output stream – to create a readline interface. The third parameter is used for autocompletion and is mostly initialized as NULL. For example, one may want to access the tab, similar to how we might press the TAB key to complete a give string.

As input parameter, createInterface uses process.stdin. As output parameter, createInterface uses process.stdout.

Code

The following code explains how a user can interact. The terminal prompts a question, “How do you feel today?”. The users enter their response. The program notes the response and terminal then responds with “Have a great day!”. The program is terminated since readline is closed in line 11.

// call readline
var readline = require('readline');
 
var rl = readline.createInterface(process.stdin, process.stdout);
rl.question("How do you feel today? ", function(answer) {
  // ask a question to interact with user.
  console.log("Have a great day!");
 
  // close the program
  rl.close();
});
Using createInterface

RELATED TAGS

nodejs

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring