Skip to content

Node.js Readline for Interactive Command-Line Interfaces

Learn how to use Node.js Readline to create interactive command-line interfaces (CLI) for your applications. Discover the basics of Readline, including reading input, prompting users, and handling multiple lines of input. Get started with code examples and build your own CLI tools.

Published

Readline is a module that provides an interface for reading input from a terminal or console. It allows you to read input line by line, making it ideal for creating interactive CLI applications.

Basic Usage

To use readline, you’ll need to create a readline interface instance and bind it to a terminal or console. Here’s an example:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

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

In this example, we create a readline interface instance and bind it to the standard input (process.stdin) and output (process.stdout) streams. We then use the question() method to prompt the user for their name and log a greeting message to the console.

Reading Multiple Lines

To read multiple lines of input, you can use the prompt() method and listen for the line event. Here’s an example:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.prompt();

rl.on('line', (line) => {
  console.log(`You entered: ${line}`);
  rl.prompt();
});

rl.on('close', () => {
  console.log('Goodbye!');
});

In this example, we create a readline interface instance and prompt the user to enter a line of text. We then listen for the line event and log the user’s input to the console. When the user presses Ctrl+D to exit, we log a goodbye message.

Example Use Case: Simple Calculator

Here’s an example of using readline to create a simple calculator:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function calculate() {
  rl.question('Enter a number: ', (num1) => {
    rl.question('Enter another number: ', (num2) => {
      const result = parseInt(num1) + parseInt(num2);
      console.log(`Result: ${result}`);
      calculate();
    });
  });
}

calculate();

In this example, we create a readline interface instance and define a calculate() function that prompts the user to enter two numbers and logs the result to the console. We then call the calculate() function recursively to create a loop.


nodejsreadlinejavascript