Node.js readline Module

Java FileNode.js Built-in Modules


Node.js'sreadlinemodule is an interface for reading data line by line from a readable stream (such asprocess.stdin). It provides a simple way to handle command-line input and is very suitable for creating interactive command-line applications.


Basic Usage

Import the readline module

To usereadlinemodule, you first need to import it:

const readline = require('readline');

Create a readline interface

Creatingreadline.Interfacean instance is the core of using this module:

Example

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

Here we created an interface that reads data from standard input (keyboard) and writes output to standard output (console).


Main Methods and Events

Reading Input Line by Line

Usequestion()method to ask the user a question and wait for an answer:

Example

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

Listening for the line event

When the user enters a line and presses Enter, thelineevent is triggered:

Example

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

Closing the Interface

Useclose()method to close the interface and release resources:

Example

rl.close();

When the interface is closed, thecloseevent is triggered:

Example

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

Advanced Features

History

readlineThe module supports command history functionality:

Example

rl.history = ['command1', 'command2'];  // Set history

Users can use the up and down arrow keys to browse historical commands.

Custom Completion

You can implement custom Tab completion functionality:

Example

rl.on('completer', (line) => {
  const completions = ['help', 'exit', 'show'];
  const hits = completions.filter((c) => c.startsWith(line));
  return [hits.length ? hits : completions, line];
});

Cursor Control

readlineProvides some methods to control the cursor:

Example

readline.cursorTo(process.stdout, 10, 5);  // Move the cursor to column 10, row 5
readline.clearLine(process.stdout, 0);     // Clear the current line
readline.clearScreenDown(process.stdout);  // Clear content below the cursor

Practical Application Examples

Create a simple command-line Q&A program

Example

const readline = require('readline');

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

const questions = [
  'What is your name?',
  'How old are you this year?',
  'What is your favorite programming language?'
];

const answers = [];

function askQuestion(i = 0) {
  if (i >= questions.length) {
    console.log('Thank you for your answers:', answers);
    return rl.close();
  }

  rl.question(questions[i], (answer) => {
    answers.push(answer);
    askQuestion(i + 1);
  });
}

askQuestion();

Create a simple command-line calculator

Example

const readline = require('readline');

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

function calculator() {
  rl.question('Please enter an expression (e.g., 2 + 3, or type exit to quit): ', (input) => {
    if (input === 'exit') {
      return rl.close();
    }

    try {
      const result = eval(input);  // Note: In real applications, avoid using eval directly
      console.log(`Result: ${result}`);
    } catch (e) {
      console.log('Invalid expression');
    }

    calculator();  // Recursively call to continue the next calculation
  });
}

calculator();

Security Considerations

  1. Avoid using eval(): The calculator example above usedeval(), which is unsafe in production environments because it executes any input JavaScript code. In real applications, you should use a dedicated expression parser.

  2. Input validation: Always validate user input to prevent injection attacks or other security issues.

  3. Error handling: Add appropriate error handling for all asynchronous operations.


Summary

Node.js'sreadlinemodule is a powerful tool for building interactive command-line tools. With it, we can:

  • Easily get user input
  • Create Q&A-style interactive interfaces
  • Implement command history
  • Add Tab completion functionality
  • Control terminal cursor and output

MasterreadlineThe module is an important step in developing Node.js command-line tools. I hope this article helps you understand and use this module.

Java FileNode.js Built-in Modules

Other Extensions