nodejs
  1. nodejs-readline

Node.js Readline

In Node.js, the readline module provides an interface for reading data from a Readable stream (like process.stdin) on a line-by-line basis. It's useful for building command-line interfaces and other interactive programs.

Syntax

The basic syntax for reading lines using the readline module and a Readable stream is:

const readline = require('readline');

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

rl.on('line', (input) => {
    console.log(`Received: ${input}`);
});

This code creates an instance of the readline interface and sets it up to use the standard input and output streams (stdin and stdout). When a line of input is received, the 'line' event is triggered and the callback function is executed.

Example

Here's an example program that uses the readline module to prompt the user for their name and then prints it back to them:

const readline = require('readline');

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

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

This code uses the rl.question() method to prompt the user for their name and pass the input to a callback function that prints a greeting with their name. The rl.close() method is used to close the readline interface.

Output

When we run the example code above, the output will be:

What is your name? John
Hello, John!

This is because we entered "John" when prompted for our name, and the program printed a greeting with that name.

Explanation

In the example above, we use the readline module to create an interface that reads lines of input from the user. We then use the rl.question() method to prompt the user for their name and pass the input to a callback function that prints a greeting with their name.

Use

The readline module is useful for building command-line interfaces and other interactive programs that need to read input from the user on a line-by-line basis. It's often used in conjunction with other Node.js modules like chalk and figlet to create more elaborate CLI applications.

Important Points

  • The rl.question() method is used to prompt the user for input and read the input when it is typed.
  • The rl.close() method is used to close the readline interface after we're done reading input.
  • When using the readline module, be aware of any encoding issues that could arise from reading input from the console or other sources.

Summary

In this tutorial, we discussed how to use the readline module in Node.js to read input from a Readable stream (like process.stdin) on a line-by-line basis. We covered the syntax, example, output, explanation, use, and important points of the readline module. With this knowledge, you can now build more interactive CLI applications using Node.js.

Published on: