Node.js Readline() Module
Last Updated :
07 Jan, 2025
Readline Module in Node.js allows the reading of input stream line by line. This module wraps up the process standard output and process standard input objects.
The Readline module makes it easier to input and read the output given by the user.
Syntax:
// Import the module
const readline = require('readline');
// Use the Methods Methods
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
The Readline module comes with different methods to interact with the user.
Common Readline Methods
Method | Description |
---|
rl.question(query, callback) | Displays the query to the user and calls the callback with the user input as an argument. |
rl.prompt() | Displays the configured prompt to the user. |
rl.on('line', callback) | Registers a callback to be executed each time the user enters a line of input. |
rl.close() | Closes the readline interface, freeing up resources and stopping the event loop. |
rl.pause() | Pauses the input stream, stopping the line event from being emitted temporarily. |
rl.resume() | Resumes the input stream after it has been paused. |
rl.setPrompt(prompt) | Sets the prompt to display to the user, useful for customizing prompts dynamically. |
rl.write(data) | Writes data to the output stream or simulates user input if the data is a string. |
rl.clearLine(dir) | Clears the current line of input based on the direction (-1 , 0 , 1 ). |
rl.clearScreenDown() | Clears the screen from the current position of the cursor downwards. |
The Readline module allows interactive command-line input in Node.js.
User Interaction
createInterface:
For the interaction, we will first create an interface for the input and output. For creating an interface, write the following code -
JavaScript
const readline = require("readline");
let rl = readline.createInterface(
process.stdin, process.stdout
);
Here, the createInterface() method takes two arguments. The first argument will be for the standard input and the second one will be for reading the standard output.
rl.question
JavaScript
rl.question('What is your age? ', (age) => {
console.log('Your age is: ' + age);
});
Here, rl.question() method is used for asking questions from the user and reading their reply (output). The first parameter is used to ask the question and the second parameter is a callback function that will take the output from the user as the parameter and return it to the console.
The output for the above code will be -
What is your age? 20
Your age is: 20
Here, the problem is it will not exit the application and it will keep asking for the inputs. To resolve this issue, rl.close() method is used. This method will close the interface. To use it in the application, write the following -
JavaScript
rl.question('What is your age? ', (age) => {
console.log('Your age is: ' + age);
rl.close();
});
setPrompt
A setPrompt() method is used to set the particular statement to the console. prompt() method for displaying the statement which is set in setPrompt() Method. Therefore, write the following code -
JavaScript
const readline = require('readline');
let rl = readline.createInterface(
process.stdin, process.stdout
);
rl.setPrompt(`What is your age? `);
rl.prompt()
This code will take input from the user.
rl.on
Now, we need a listener for reading the input from the user and displaying it to the console. For this purpose, Readline Module has a listener method called on that will take two parameters. The first parameter will the event and the second parameter will be a callback function that will return the output to the console. For example -
JavaScript
const readline = require('readline');
const rl = readline.createInterface(
process.stdin, process.stdout);
rl.setPrompt(`What is your age? `);
rl.prompt();
rl.on('line', (age) => {
console.log(`Age received by the user: ${age}`);
rl.close();
});
Here, rl.on() method takes the first argument as a line event. This event is invoked whenever the user presses Enter key. The output for the above code will be -
What is your age? 20
Age received by the user: 20
Events:
Along with the listener, readline module also comes with the event's properties. Let us learn about the various events.
- close: This event is invoked when either rl.close() method is called or when the user presses ctrl + c to close the interface.
- line: This event is invoked whenever the user presses Enter or return keys. This event is called the listener function.
For example:
JavaScript
rl.on('line', (input) => {
console.log(`Input Received: ${input}`);
rl.close();
});
- pause: This event is invoked when the input stream is paused. For example -
JavaScript
rl.on('pause', () => {
console.log('Paused Event is invoked');
});
- The output for the above code will be:
Paused Event is invoked
- resume: This event is invoked whenever the input is resumed. For example:
JavaScript
rl.on('resume', () => {
console.log('Resume Event is invoked.');
});
- SIGINT: This event is invoked whenever the user press ctrl + c button. If there are no event listeners registered when the SIGINT is invoked, then the pause event will be invoked. For example -
JavaScript
rl.on('SIGINT', () => {
rl.question('Exit (y or n)? ', (input) => {
if (input.match(/^y(es)?$/i)) { rl.pause(); }
});
});
- This code will ask the given question if the ctrl + c key is pressed by the user. Here, if the provided input will match with y or yes, then the pause() method will be called on the interface.
- SIGTSTP: This event is invoked whenever the user gives ctrl + z input. This input is known as SIGTSTP. If a user does not provide the SIGTSTP input, then the current running process will be sent to the background. For example -
JavaScript
rl.on('SIGTSTP', () => {
console.log('SIGTSTP event is invoked.');
})
- SIGCONT: This event is invoked when a process that was sent to the background using SIGTSTP is again brought back to the front-running process. For example:
JavaScript
rl.on('SIGCONT', () => {
console.log('SIGCONT event is invoked.');
rl.prompt();
})
Conclusion
The readline module is important for creating interactive commandline tools in Node JS. It also provide responsive and flexible inputs.
In this article, we learned about the Readline Module in Node.js. Also, we learned about its various implementations using methods, variables, events, and listeners.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read