read - User Input from Stdin

5.0.1 · active · verified Sun Apr 19

The `read` package provides a utility for securely and flexibly reading user input from `stdin` in Node.js applications. It serves as an enhanced alternative to Node's built-in `readline.question()` method, offering additional features such as silent input (e.g., for passwords), character replacement during silent input, input timeouts, default values, editable default values, terminal forcing, and auto-completion via a `completer` option. As of version 5.0.1, the package is actively maintained by the npm team and targets modern Node.js environments, requiring `^20.17.0 || >=22.9.0`. Major releases (e.g., v2.0.0, v3.0.0, v4.0.0, v5.0.0) typically introduce breaking changes related to Node.js version compatibility or API shifts, with minor releases adding new features like the `history` parameter in v4.1.0. The library primarily uses a Promise-based API for handling input, reflecting modern JavaScript asynchronous patterns.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates prompting for username, a silent password input with timeout and character replacement, and an editable default value for favorite color, using the `read` function and its options.

import { read } from 'read';

async function getUserInput() {
  try {
    const username = await read({ prompt: 'Username: ' });
    console.log(`Hello, ${username}!`);

    const password = await read({
      prompt: 'Password: ',
      silent: true,
      replace: '*',
      timeout: 15000 // 15 seconds
    });
    console.log('Password received (not echoed).');

    const favoriteColor = await read({
      prompt: 'What is your favorite color? ',
      default: 'blue',
      edit: true,
    });
    console.log(`Your favorite color is: ${favoriteColor}`);

  } catch (error) {
    if (error instanceof Error && error.message === 'timed out') {
      console.error('Input timed out. Please try again.');
    } else {
      console.error('An error occurred:', error);
    }
    process.exit(1);
  }
}

getUserInput();

view raw JSON →