Convert Figma logo to code with AI

SBoudrias logoInquirer.js

A collection of common interactive command line user interfaces.

20,007
1,298
20,007
82

Top Related Projects

8,821

❯ Lightweight, beautiful and user-friendly interactive prompts

Stylish, intuitive and user-friendly prompts, for Node.js. Used by eslint, webpack, yarn, pm2, pnpm, RedwoodJS, FactorJS, salesforce, Cypress, Google Lighthouse, Generate, tencent cloudbase, lint-staged, gluegun, hygen, hardhat, AWS Amplify, GitHub Actions Toolkit, @airbnb/nimbus, and many others! Please follow Enquirer's author: https://github.com/jonschlinkert

node.js command-line interfaces made easy

9,080

Elegant terminal spinner

Quick Overview

Inquirer.js is a popular Node.js library for creating interactive command-line interfaces. It provides a collection of common prompts, such as input, password, list, and checkbox, making it easy to build engaging CLI applications and gather user input in a structured manner.

Pros

  • Easy to use and intuitive API
  • Supports a wide variety of prompt types
  • Highly customizable with theming and styling options
  • Actively maintained with regular updates

Cons

  • Limited to command-line interfaces, not suitable for graphical applications
  • May have a slight learning curve for complex prompt configurations
  • Performance can be impacted when handling large datasets in certain prompt types

Code Examples

  1. Basic input prompt:
import inquirer from 'inquirer';

const answer = await inquirer.prompt([
  {
    type: 'input',
    name: 'username',
    message: 'What is your name?',
  }
]);
console.log(`Hello, ${answer.username}!`);
  1. List selection prompt:
import inquirer from 'inquirer';

const answer = await inquirer.prompt([
  {
    type: 'list',
    name: 'color',
    message: 'What is your favorite color?',
    choices: ['Red', 'Blue', 'Green', 'Yellow'],
  }
]);
console.log(`You chose ${answer.color}`);
  1. Checkbox prompt:
import inquirer from 'inquirer';

const answer = await inquirer.prompt([
  {
    type: 'checkbox',
    name: 'toppings',
    message: 'Select pizza toppings:',
    choices: [
      { name: 'Pepperoni' },
      { name: 'Mushrooms' },
      { name: 'Onions' },
      { name: 'Sausage' },
      { name: 'Extra cheese' }
    ],
  }
]);
console.log('You selected:', answer.toppings);

Getting Started

To use Inquirer.js in your project, follow these steps:

  1. Install the package:

    npm install inquirer
    
  2. Import and use in your JavaScript file:

    import inquirer from 'inquirer';
    
    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'name',
        message: 'What is your name?',
      },
      {
        type: 'list',
        name: 'action',
        message: 'What would you like to do?',
        choices: ['Create', 'Read', 'Update', 'Delete'],
      }
    ]);
    
    console.log('Answers:', answers);
    

This example demonstrates how to create a simple CLI application that asks for the user's name and presents a list of actions to choose from.

Competitor Comparisons

8,821

❯ Lightweight, beautiful and user-friendly interactive prompts

Pros of prompts

  • Lightweight and minimal with a smaller bundle size
  • Simpler API with less configuration required
  • Supports both promise-based and callback-style usage

Cons of prompts

  • Fewer built-in prompt types compared to Inquirer.js
  • Less extensive documentation and community support
  • Limited customization options for complex scenarios

Code Comparison

Inquirer.js:

const inquirer = require('inquirer');

inquirer
  .prompt([
    {
      type: 'input',
      name: 'name',
      message: 'What is your name?',
    },
  ])
  .then((answers) => {
    console.log(`Hello, ${answers.name}!`);
  });

prompts:

const prompts = require('prompts');

(async () => {
  const response = await prompts({
    type: 'text',
    name: 'name',
    message: 'What is your name?'
  });

  console.log(`Hello, ${response.name}!`);
})();

Both libraries provide similar functionality for creating interactive command-line interfaces. Inquirer.js offers more features and customization options, making it suitable for complex applications. prompts, on the other hand, is more lightweight and straightforward, ideal for simpler use cases or when bundle size is a concern. The choice between the two depends on the specific requirements of your project and personal preference.

Stylish, intuitive and user-friendly prompts, for Node.js. Used by eslint, webpack, yarn, pm2, pnpm, RedwoodJS, FactorJS, salesforce, Cypress, Google Lighthouse, Generate, tencent cloudbase, lint-staged, gluegun, hygen, hardhat, AWS Amplify, GitHub Actions Toolkit, @airbnb/nimbus, and many others! Please follow Enquirer's author: https://github.com/jonschlinkert

Pros of Enquirer

  • Faster performance due to its lightweight design and minimal dependencies
  • More modern and flexible API, allowing for easier customization of prompts
  • Better support for asynchronous operations and promises

Cons of Enquirer

  • Smaller community and ecosystem compared to Inquirer.js
  • Less extensive documentation and fewer examples available
  • Some users may find the API less intuitive, especially if they're used to Inquirer.js

Code Comparison

Inquirer.js:

const inquirer = require('inquirer');
inquirer.prompt([
  {
    type: 'input',
    name: 'username',
    message: 'Enter your username:'
  }
]).then(answers => {
  console.log('Username:', answers.username);
});

Enquirer:

const { prompt } = require('enquirer');
prompt({
  type: 'input',
  name: 'username',
  message: 'Enter your username:'
}).then(answer => {
  console.log('Username:', answer.username);
});

Both libraries offer similar functionality for creating command-line prompts, but Enquirer provides a more streamlined API and better performance. Inquirer.js has a larger community and more extensive documentation, which can be beneficial for beginners or projects requiring widespread support. The choice between the two depends on specific project requirements, performance needs, and developer preferences.

node.js command-line interfaces made easy

Pros of Commander.js

  • Lightweight and focused on command-line argument parsing
  • Simple and straightforward API for defining commands and options
  • Built-in help generation and version information

Cons of Commander.js

  • Limited interactive input capabilities compared to Inquirer.js
  • Less flexibility for complex user prompts and input validation
  • Primarily designed for command-line interfaces, not as versatile for other input scenarios

Code Comparison

Commander.js:

const program = require('commander');

program
  .version('0.1.0')
  .option('-p, --peppers', 'Add peppers')
  .option('-c, --cheese <type>', 'Add cheese')
  .parse(process.argv);

Inquirer.js:

const inquirer = require('inquirer');

inquirer
  .prompt([
    {
      type: 'confirm',
      name: 'peppers',
      message: 'Add peppers?'
    },
    {
      type: 'list',
      name: 'cheese',
      message: 'What type of cheese?',
      choices: ['Cheddar', 'Mozzarella', 'Parmesan']
    }
  ])
  .then(answers => {
    console.log(answers);
  });

Commander.js is more suitable for parsing command-line arguments and options, while Inquirer.js excels at creating interactive command-line interfaces with various question types and input validation. Commander.js has a simpler API for defining commands, while Inquirer.js offers more flexibility for complex user interactions.

9,080

Elegant terminal spinner

Pros of ora

  • Lightweight and focused on providing elegant terminal spinners
  • Simple API for creating and managing loading indicators
  • Supports custom spinner styles and colors

Cons of ora

  • Limited to spinner/loading functionality
  • Less versatile for complex user interactions
  • Doesn't support input prompts or user choices

Code Comparison

Inquirer.js:

const inquirer = require('inquirer');

inquirer
  .prompt([
    {
      type: 'input',
      name: 'username',
      message: 'Enter your username:',
    },
  ])
  .then((answers) => {
    console.log('Username:', answers.username);
  });

ora:

const ora = require('ora');

const spinner = ora('Loading...').start();

setTimeout(() => {
  spinner.succeed('Data loaded successfully');
}, 2000);

Summary

Inquirer.js is a comprehensive library for creating interactive command-line interfaces, offering various question types and complex user interactions. It's ideal for applications requiring user input and decision-making.

ora, on the other hand, specializes in creating elegant terminal spinners and loading indicators. It's perfect for displaying progress or status updates in CLI applications but lacks the ability to gather user input or present choices.

Choose Inquirer.js for complex user interactions and input gathering, and ora for simple, visually appealing loading indicators in your CLI applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Inquirer Logo

Inquirer

npm FOSSA Status

A collection of common interactive command line user interfaces.

List prompt

Give it a try in your own terminal!

npx @inquirer/demo@latest

Installation

npm yarn
npm install @inquirer/prompts
yarn add @inquirer/prompts

[!NOTE] Inquirer recently underwent a rewrite from the ground up to reduce the package size and improve performance. The previous version of the package is still maintained (though not actively developed), and offered hundreds of community contributed prompts that might not have been migrated to the latest API. If this is what you're looking for, the previous package is over here.

Usage

import { input } from '@inquirer/prompts';

const answer = await input({ message: 'Enter your name' });

Prompts

Input

Input prompt

import { input } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Select

Select prompt

import { select } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Checkbox

Checkbox prompt

import { checkbox } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Confirm

Confirm prompt

import { confirm } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Search

search prompt

import { search } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Password

Password prompt

import { password } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Expand

Expand prompt closed Expand prompt expanded

import { expand } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Editor

Launches an instance of the users preferred editor on a temporary file. Once the user exits their editor, the content of the temporary file is read as the answer. The editor used is determined by reading the $VISUAL or $EDITOR environment variables. If neither of those are present, the OS default is used (notepad on Windows, vim on Mac or Linux.)

import { editor } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Number

Very similar to the input prompt, but with built-in number validation configuration option.

import { number } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Raw List

Raw list prompt

import { rawlist } from '@inquirer/prompts';

See documentation for usage example and options documentation.

Create your own prompts

The API documentation is over here, and our testing utilities here.

Advanced usage

All inquirer prompts are a function taking 2 arguments. The first argument is the prompt configuration (unique to each prompt). The second is providing contextual or runtime configuration.

The context options are:

PropertyTypeRequiredDescription
inputNodeJS.ReadableStreamnoThe stdin stream (defaults to process.stdin)
outputNodeJS.WritableStreamnoThe stdout stream (defaults to process.stdout)
clearPromptOnDonebooleannoIf true, we'll clear the screen after the prompt is answered
signalAbortSignalnoAn AbortSignal to cancel prompts asynchronously

Example:

import { confirm } from '@inquirer/prompts';

const allowEmail = await confirm(
  { message: 'Do you allow us to send you email?' },
  {
    output: new Stream.Writable({
      write(chunk, _encoding, next) {
        // Do something
        next();
      },
    }),
    clearPromptOnDone: true,
  },
);

Canceling prompt

This can preferably be done with either an AbortController or AbortSignal.

// Example 1: using built-in AbortSignal utilities
import { confirm } from '@inquirer/prompts';

const answer = await confirm({ ... }, { signal: AbortSignal.timeout(5000) });
// Example 1: implementing custom cancellation logic
import { confirm } from '@inquirer/prompts';

const controller = new AbortController();
setTimeout(() => {
  controller.abort(); // This will reject the promise
}, 5000);

const answer = await confirm({ ... }, { signal: controller.signal });

Alternatively, all prompt functions are returning a cancelable promise. This special promise type has a cancel method that'll cancel and cleanup the prompt.

On calling cancel, the answer promise will become rejected.

import { confirm } from '@inquirer/prompts';

const promise = confirm(...); // Warning: for this pattern to work, `await` cannot be used.

promise.cancel();

Recipes

Get answers in an object

When asking many questions, you might not want to keep one variable per answer everywhere. In which case, you can put the answer inside an object.

import { input, confirm } from '@inquirer/prompts';

const answers = {
  firstName: await input({ message: "What's your first name?" }),
  allowEmail: await confirm({ message: 'Do you allow us to send you email?' }),
};

console.log(answers.firstName);

Ask a question conditionally

Maybe some questions depend on some other question's answer.

import { input, confirm } from '@inquirer/prompts';

const allowEmail = await confirm({ message: 'Do you allow us to send you email?' });

let email;
if (allowEmail) {
  email = await input({ message: 'What is your email address' });
}

Get default value after timeout

import { input } from '@inquirer/prompts';

const answer = await input(
  { message: 'Enter a value (timing out in 5 seconds)' },
  { signal: AbortSignal.timeout(5000) },
).catch((error) => {
  if (error.name === 'AbortPromptError') {
    return 'Default value';
  }

  throw error;
});

Using as pre-commit/git hooks, or scripts

By default scripts ran from tools like husky/lint-staged might not run inside an interactive shell. In non-interactive shell, Inquirer cannot run, and users cannot send keypress events to the process.

For it to work, you must make sure you start a tty (or "interactive" input stream.)

If those scripts are set within your package.json, you can define the stream like so:

  "precommit": "my-script < /dev/tty"

Or if in a shell script file, you'll do it like so: (on Windows that's likely your only option)

#!/bin/sh
exec < /dev/tty

node my-script.js

Wait for config

Maybe some question configuration require to await a value.

import { confirm } from '@inquirer/prompts';

const answer = await confirm({ message: await getMessage() });

Community prompts

If you created a cool prompt, send us a PR adding it to the list below!

Interactive List Prompt
Select a choice either with arrow keys + Enter or by pressing a key associated with a choice.

? Choose an option:
>   Run command (D)
    Quit (Q)

Action Select Prompt
Choose an item from a list and choose an action to take by pressing a key.

? Choose a file Open <O> Edit <E> Delete <X>
❯ image.png
  audio.mp3
  code.py

Table Multiple Prompt
Select multiple answer from a table display.

Choose between choices? (Press <space> to select, <Up and Down> to move rows,
<Left and Right> to move columns)

┌──────────┬───────┬───────┐
│ 1-2 of 2 │ Yes?  │ No?   |
├──────────┼───────┼───────┤
│ Choice 1 │ [ ◯ ] │   ◯   |
├──────────┼───────┼───────┤
│ Choice 2 │   ◯   │   ◯   |
└──────────┴───────┴───────┘

Toggle Prompt
Confirm with a toggle. Select a choice with arrow keys + Enter.

? Do you want to continue? no / yes

Sortable Checkbox Prompt
The same as built-in checkbox prompt, but also allowing to reorder choices using ctrl+up/down.

? Which PRs and in what order would you like to merge? (Press <space> to select, <a> to toggle all, <i> to invert selection, <ctrl+up> to move item up, <ctrl+down> to move item down, and <enter> to proceed)
❯ ◯ PR 1
  ◯ PR 2
  ◯ PR 3

Multi Select Prompt

An inquirer select that supports multiple selections and filtering/searching.

? Choose your OS, IDE, PL, etc. (Press <tab> to select/deselect, <backspace> to remove selected
option, <enter> to select option)
>>  vue
>[ ] vue
 [ ] vuejs
 [ ] fuelphp
 [ ] venv
 [ ] vercel
 (Use arrow keys to reveal more options)

File Selector Prompt
A file selector, you can navigate freely between directories, choose what type of files you want to allow and it is fully customizable.

? Select a file:
/main/path/
├── folder1/
├── folder2/
├── folder3/
├── file1.txt
├── file2.pdf
└── file3.jpg (not allowed)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Use ↑↓ to navigate through the list
Press <esc> to navigate to the parent directory
Press <enter> to select a file or navigate to a directory

License

Copyright (c) 2023 Simon Boudrias (twitter: @vaxilart)
Licensed under the MIT license.

NPM DownloadsLast 30 Days