Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 10 - User Input

10.1 Reading User Input

The readline Package

readline is a built-in Node.js package that provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time.

Usage

  • Installation: The readline package is included by default with Node.js, so no installation is necessary.

#Example

This example shows how to use the readline package to prompt the user for input and display a response.

// Import Package
const readline = require('readline');

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

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

Example: Asking for User Name and Age

If you want to ask the user for their name and age and then display it, you can create multiple nested rl.question calls:

// Import Package
const readline = require('readline');

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

// Asking for User Name and Age
rl.question('What is your name? ', (name) => {
  rl.question('What is your age? ', (age) => {
    console.log(`Hello, ${name}! Your age is ${age}.`);
    rl.close();
  });
});

This extended example demonstrates how to handle multiple inputs by nesting rl.question calls, allowing you to collect and display both the user's name and age.