Node.js Readline for Interactive Command-Line Interfaces

Node.js provides a built-in module called readline that allows developers to create interactive command-line interfaces (CLI) for their applications. In this post, we’ll explore the basics of using readline and provide code examples to get you started.

What is Readline?

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.

Latest blog posts

Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.