Enquirer

Stylish, intuitive and user-friendly prompts, for Node.js. Used by eslint, ...

README

Enquirer

version travis downloads


Stylish CLI prompts that are user-friendly, intuitive and easy to create.
>_ Prompts should be more like conversations than inquisitions▌

(Example shows Enquirer's Survey Prompt) Enquirer Survey Prompt
The terminal in all examples is Hyper, theme is hyper-monokai-extended.

See more prompt examples



Created by [jonschlinkert][jon] and [doowb][brian], Enquirer is fast, easy to use, and lightweight enough for small projects, while also being powerful and customizable enough for the most advanced use cases.

- Fast - Loads in ~4ms (that's about _3-4 times faster than a single frame of a HD movie at 60fps_)
- Lightweight - Only one dependency, the excellent ansi-colors by Brian Woodward.
- Easy to implement - Uses promises and async/await and sensible defaults to make prompts easy to create and implement.
- Easy to use - Thrill your users with a better experience! Navigating around input and choices is a breeze. You can even create quizzes, or record and playback key bindings to aid with tutorials and videos.
- Intuitive - Keypress combos are available to simplify usage.
- Flexible - All prompts can be used standalone or chained together.
- Stylish - Easily override semantic styles and symbols for any part of the prompt.
- Extensible - Easily create and use custom prompts by extending Enquirer's built-in prompts.
- Pluggable - Add advanced features to Enquirer using plugins.
- Validation - Optionally validate user input with any prompt.
- Well tested - All prompts are well-tested, and tests are easy to create without having to use brittle, hacky solutions to spy on prompts or "inject" values.
- Examples - There are numerous examples available to help you get started.

If you like Enquirer, please consider starring or tweeting about this project to show your support. Thanks!

[issue]: https://github.com/enquirer/enquirer/issues/new
[pulls]: https://github.com/enquirer/enquirer/pulls
[jon]: https://github.com/jonschlinkert
[brian]: https://github.com/doowb

>_ Ready to start making prompts your users will love? ▌
Enquirer Select Prompt with heartbeat example



❯ Getting started


Get started with Enquirer, the most powerful and easy-to-use Node.js library for creating interactive CLI prompts.


❯ Install

Install with npm:

  1. ```sh
  2. $ npm install enquirer --save
  3. ```
Install with yarn:

  1. ```sh
  2. $ yarn add enquirer
  3. ```

Install Enquirer with NPM


_(Requires Node.js 8.6 or higher. Please let us know if you need support for an earlier version by creating an issue.)_

❯ Usage

Single prompt


The easiest way to get started with enquirer is to pass a question object to theprompt method.

  1. ``` js
  2. const { prompt } = require('enquirer');

  3. const response = await prompt({
  4.   type: 'input',
  5.   name: 'username',
  6.   message: 'What is your username?'
  7. });

  8. console.log(response); // { username: 'jonschlinkert' }
  9. ```

_(Examples with await need to be run inside an async function)_

Multiple prompts


Pass an array of "question" objects to run a series of prompts.

  1. ``` js
  2. const response = await prompt([
  3.   {
  4.     type: 'input',
  5.     name: 'name',
  6.     message: 'What is your name?'
  7.   },
  8.   {
  9.     type: 'input',
  10.     name: 'username',
  11.     message: 'What is your username?'
  12.   }
  13. ]);

  14. console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' }
  15. ```

Different ways to run enquirer


1. By importing the specific built-in prompt


  1. ``` js
  2. const { Confirm } = require('enquirer');

  3. const prompt = new Confirm({
  4.   name: 'question',
  5.   message: 'Did you like enquirer?'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Answer:', answer));
  9. ```

2. By passing the options to prompt


  1. ``` js
  2. const { prompt } = require('enquirer');

  3. prompt({
  4.   type: 'confirm',
  5.   name: 'question',
  6.   message: 'Did you like enquirer?'
  7. })
  8.   .then(answer => console.log('Answer:', answer));
  9. ```


❯ Enquirer

Enquirer is a prompt runner

Add Enquirer to your JavaScript project with following line of code.

  1. ``` js
  2. const Enquirer = require('enquirer');
  3. ```

The main export of this library is the Enquirer class, which has methods and features designed to simplify running prompts.

  1. ``` js
  2. const { prompt } = require('enquirer');
  3. const question = [
  4.   {
  5.     type: 'input',
  6.     name: 'username',
  7.     message: 'What is your username?'
  8.   },
  9.   {
  10.     type: 'password',
  11.     name: 'password',
  12.     message: 'What is your password?'
  13.   }
  14. ];

  15. let answers = await prompt(question);
  16. console.log(answers);
  17. ```

Prompts control how values are rendered and returned

Each individual prompt is a class with special features and functionality for rendering the types of values you want to show users in the terminal, and subsequently returning the types of values you need to use in your application.

How can I customize prompts?

Below in this guide you will find information about creating custom prompts. For now, we'll focus on how to customize an existing prompt.

All of the individual prompt classes in this library are exposed as static properties on Enquirer. This allows them to be used directly without usingenquirer.prompt().

Use this approach if you need to modify a prompt instance, or listen for events on the prompt.

Example

  1. ``` js
  2. const { Input } = require('enquirer');
  3. const prompt = new Input({
  4.   name: 'username',
  5.   message: 'What is your username?'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Username:', answer))
  9.   .catch(console.error);
  10. ```

Enquirer API


Create an instance of Enquirer.

Params

options {Object}: (optional) Options to use with all prompts.    
answers {Object}: (optional) Answers object to initialize with.    

Example

  1. ``` js
  2. const Enquirer = require('enquirer');
  3. const enquirer = new Enquirer();
  4. ```

Register a custom prompt type.

Params

type {String}    
fn {Function|Prompt}: Prompt class, or a function that returns a Prompt class.    
returns {Object}: Returns the Enquirer instance  

Example

  1. ``` js
  2. const Enquirer = require('enquirer');
  3. const enquirer = new Enquirer();
  4. enquirer.register('customType', require('./custom-prompt'));
  5. ```

Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user.

Params

questions {Array|Object}: Options objects for one or more prompts to run.    
returns {Promise}: Promise that returns an "answers" object with the user's responses.  

Example

  1. ``` js
  2. const Enquirer = require('enquirer');
  3. const enquirer = new Enquirer();

  4. const response = await enquirer.prompt({
  5.   type: 'input',
  6.   name: 'username',
  7.   message: 'What is your username?'
  8. });
  9. console.log(response);
  10. ```

Use an enquirer plugin.

Params

plugin {Function}: Plugin function that takes an instance of Enquirer.    
returns {Object}: Returns the Enquirer instance.  

Example

  1. ``` js
  2. const Enquirer = require('enquirer');
  3. const enquirer = new Enquirer();
  4. const plugin = enquirer => {
  5.   // do stuff to enquire instance
  6. };
  7. enquirer.use(plugin);
  8. ```

Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user.

Params

questions {Array|Object}: Options objects for one or more prompts to run.    
returns {Promise}: Promise that returns an "answers" object with the user's responses.  

Example

  1. ``` js
  2. const { prompt } = require('enquirer');
  3. const response = await prompt({
  4.   type: 'input',
  5.   name: 'username',
  6.   message: 'What is your username?'
  7. });
  8. console.log(response);
  9. ```

❯ Prompts

This section is about Enquirer's prompts: what they look like, how they work, how to run them, available options, and how to customize the prompts or create your own prompt concept.

Getting started with Enquirer's prompts

- Prompt - The basePrompt class used by other prompts
- Prompt Types - The basePrompt class used by other prompts
- Custom Prompts - Enquirer 2.0 introduced the concept of prompt "types", with the goal of making custom prompts easier than ever to create and use.

Prompt


The base Prompt class is used to create all other prompts.

  1. ``` js
  2. const { Prompt } = require('enquirer');
  3. class MyCustomPrompt extends Prompt {}
  4. ```

See the documentation for creating custom prompts to learn more about how this works.

Prompt Options


Each prompt takes an options object (aka "question" object), that implements the following interface:

  1. ``` js
  2. {
  3.   // required
  4.   type: string | function,
  5.   name: string | function,
  6.   message: string | function | async function,

  7.   // optional
  8.   skip: boolean | function | async function,
  9.   initial: string | function | async function,
  10.   format: function | async function,
  11.   result: function | async function,
  12.   validate: function | async function,
  13. }
  14. ```
Each property of the options object is described below:

**Property****Required?****Type****Description**
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`type`yes`string\|function`Enquirer
`name`yes`string\|function`Used
`message`yes`string\|function`The
`skip`no`boolean\|function`If
`initial`no`string\|function`The
`format`no`function`Function
`result`no`function`Function
`validate`no`function`Function

Example usage

  1. ``` js
  2. const { prompt } = require('enquirer');

  3. const question = {
  4.   type: 'input',
  5.   name: 'username',
  6.   message: 'What is your username?'
  7. };

  8. prompt(question)
  9.   .then(answer => console.log('Answer:', answer))
  10.   .catch(console.error);
  11. ```

❯ Built-in prompts



AutoComplete Prompt


Prompt that auto-completes as the user types, and returns the selected value as a string.

Enquirer AutoComplete Prompt


Example Usage

  1. ``` js
  2. const { AutoComplete } = require('enquirer');

  3. const prompt = new AutoComplete({
  4.   name: 'flavor',
  5.   message: 'Pick your favorite flavor',
  6.   limit: 10,
  7.   initial: 2,
  8.   choices: [
  9.     'Almond',
  10.     'Apple',
  11.     'Banana',
  12.     'Blackberry',
  13.     'Blueberry',
  14.     'Cherry',
  15.     'Chocolate',
  16.     'Cinnamon',
  17.     'Coconut',
  18.     'Cranberry',
  19.     'Grape',
  20.     'Nougat',
  21.     'Orange',
  22.     'Pear',
  23.     'Pineapple',
  24.     'Raspberry',
  25.     'Strawberry',
  26.     'Vanilla',
  27.     'Watermelon',
  28.     'Wintergreen'
  29.   ]
  30. });

  31. prompt.run()
  32.   .then(answer => console.log('Answer:', answer))
  33.   .catch(console.error);
  34. ```

AutoComplete Options

OptionTypeDefaultDescription
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`highlight``function``dim`The
`multiple``boolean``false`Allow
`suggest``function`GreedyFunction
`initial``number`0Preselected
`footer``function`NoneFunction

Related prompts


↑ back to: Getting Started · Prompts


BasicAuth Prompt


Prompt that asks for username and password to authenticate the user. The default implementation of authenticate function in BasicAuth prompt is to compare the username and password with the values supplied while running the prompt. The implementer is expected to override the authenticate function with a custom logic such as making an API request to a server to authenticate the username and password entered and expect a token back.

Enquirer BasicAuth Prompt


Example Usage

  1. ``` js
  2. const { BasicAuth } = require('enquirer');

  3. const prompt = new BasicAuth({
  4.   name: 'password',
  5.   message: 'Please enter your password',
  6.   username: 'rajat-sr',
  7.   password: '123',
  8.   showPassword: true
  9. });

  10. prompt
  11.   .run()
  12.   .then(answer => console.log('Answer:', answer))
  13.   .catch(console.error);
  14. ```

↑ back to: Getting Started · Prompts


Confirm Prompt


Prompt that returns true or false.

Enquirer Confirm Prompt


Example Usage

  1. ``` js
  2. const { Confirm } = require('enquirer');

  3. const prompt = new Confirm({
  4.   name: 'question',
  5.   message: 'Want to answer?'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Answer:', answer))
  9.   .catch(console.error);
  10. ```

Related prompts


↑ back to: Getting Started · Prompts


Form Prompt


Prompt that allows the user to enter and submit multiple values on a single terminal screen.

Enquirer Form Prompt


Example Usage

  1. ``` js
  2. const { Form } = require('enquirer');

  3. const prompt = new Form({
  4.   name: 'user',
  5.   message: 'Please provide the following information:',
  6.   choices: [
  7.     { name: 'firstname', message: 'First Name', initial: 'Jon' },
  8.     { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' },
  9.     { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' }
  10.   ]
  11. });

  12. prompt.run()
  13.   .then(value => console.log('Answer:', value))
  14.   .catch(console.error);
  15. ```

Related prompts


↑ back to: Getting Started · Prompts


Input Prompt


Prompt that takes user input and returns a string.

Enquirer Input Prompt


Example Usage

  1. ``` js
  2. const { Input } = require('enquirer');
  3. const prompt = new Input({
  4.   message: 'What is your username?',
  5.   initial: 'jonschlinkert'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Answer:', answer))
  9.   .catch(console.log);
  10. ```

You can use data-store to store input history that the user can cycle through (see source).

Related prompts


↑ back to: Getting Started · Prompts


Invisible Prompt


Prompt that takes user input, hides it from the terminal, and returns a string.

Enquirer Invisible Prompt


Example Usage

  1. ``` js
  2. const { Invisible } = require('enquirer');
  3. const prompt = new Invisible({
  4.   name: 'secret',
  5.   message: 'What is your secret?'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Answer:', { secret: answer }))
  9.   .catch(console.error);
  10. ```

Related prompts


↑ back to: Getting Started · Prompts


List Prompt


Prompt that returns a list of values, created by splitting the user input. The default split character is , with optional trailing whitespace.

Enquirer List Prompt


Example Usage

  1. ``` js
  2. const { List } = require('enquirer');
  3. const prompt = new List({
  4.   name: 'keywords',
  5.   message: 'Type comma-separated keywords'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Answer:', answer))
  9.   .catch(console.error);
  10. ```

Related prompts


↑ back to: Getting Started · Prompts


MultiSelect Prompt


Prompt that allows the user to select multiple items from a list of options.

Enquirer MultiSelect Prompt


Example Usage

  1. ``` js
  2. const { MultiSelect } = require('enquirer');

  3. const prompt = new MultiSelect({
  4.   name: 'value',
  5.   message: 'Pick your favorite colors',
  6.   limit: 7,
  7.   choices: [
  8.     { name: 'aqua', value: '#00ffff' },
  9.     { name: 'black', value: '#000000' },
  10.     { name: 'blue', value: '#0000ff' },
  11.     { name: 'fuchsia', value: '#ff00ff' },
  12.     { name: 'gray', value: '#808080' },
  13.     { name: 'green', value: '#008000' },
  14.     { name: 'lime', value: '#00ff00' },
  15.     { name: 'maroon', value: '#800000' },
  16.     { name: 'navy', value: '#000080' },
  17.     { name: 'olive', value: '#808000' },
  18.     { name: 'purple', value: '#800080' },
  19.     { name: 'red', value: '#ff0000' },
  20.     { name: 'silver', value: '#c0c0c0' },
  21.     { name: 'teal', value: '#008080' },
  22.     { name: 'white', value: '#ffffff' },
  23.     { name: 'yellow', value: '#ffff00' }
  24.   ]
  25. });

  26. prompt.run()
  27.   .then(answer => console.log('Answer:', answer))
  28.   .catch(console.error);

  29. // Answer: ['aqua', 'blue', 'fuchsia']
  30. ```

Example key-value pairs

Optionally, pass a result function and use the .map method to return an object of key-value pairs of the selected names and values: example

  1. ``` js
  2. const { MultiSelect } = require('enquirer');

  3. const prompt = new MultiSelect({
  4.   name: 'value',
  5.   message: 'Pick your favorite colors',
  6.   limit: 7,
  7.   choices: [
  8.     { name: 'aqua', value: '#00ffff' },
  9.     { name: 'black', value: '#000000' },
  10.     { name: 'blue', value: '#0000ff' },
  11.     { name: 'fuchsia', value: '#ff00ff' },
  12.     { name: 'gray', value: '#808080' },
  13.     { name: 'green', value: '#008000' },
  14.     { name: 'lime', value: '#00ff00' },
  15.     { name: 'maroon', value: '#800000' },
  16.     { name: 'navy', value: '#000080' },
  17.     { name: 'olive', value: '#808000' },
  18.     { name: 'purple', value: '#800080' },
  19.     { name: 'red', value: '#ff0000' },
  20.     { name: 'silver', value: '#c0c0c0' },
  21.     { name: 'teal', value: '#008080' },
  22.     { name: 'white', value: '#ffffff' },
  23.     { name: 'yellow', value: '#ffff00' }
  24.   ],
  25.   result(names) {
  26.    return this.map(names);
  27.   }
  28. });

  29. prompt.run()
  30.   .then(answer => console.log('Answer:', answer))
  31.   .catch(console.error);

  32. // Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' }
  33. ```

Related prompts


↑ back to: Getting Started · Prompts


Numeral Prompt


Prompt that takes a number as input.

Enquirer Numeral Prompt


Example Usage

  1. ``` js
  2. const { NumberPrompt } = require('enquirer');

  3. const prompt = new NumberPrompt({
  4.   name: 'number',
  5.   message: 'Please enter a number'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Answer:', answer))
  9.   .catch(console.error);
  10. ```

Related prompts


↑ back to: Getting Started · Prompts


Password Prompt


Prompt that takes user input and masks it in the terminal. Also see the invisible prompt

Enquirer Password Prompt


Example Usage

  1. ``` js
  2. const { Password } = require('enquirer');

  3. const prompt = new Password({
  4.   name: 'password',
  5.   message: 'What is your password?'
  6. });

  7. prompt.run()
  8.   .then(answer => console.log('Answer:', answer))
  9.   .catch(console.error);
  10. ```

Related prompts


↑ back to: Getting Started · Prompts


Quiz Prompt


Prompt that allows the user to play multiple-choice quiz questions.

Enquirer Quiz Prompt


Example Usage

  1. ``` js
  2. const { Quiz } = require('enquirer');

  3. const prompt = new Quiz({
  4.   name: 'countries',
  5.   message: 'How many countries are there in the world?',
  6.   choices: ['165', '175', '185', '195', '205'],
  7.   correctChoice: 3
  8. });

  9. prompt
  10.   .run()
  11.   .then(answer => {
  12.     if (answer.correct) {
  13.       console.log('Correct!');
  14.     } else {
  15.       console.log(`Wrong! Correct answer is ${answer.correctAnswer}`);
  16.     }
  17.   })
  18.   .catch(console.error);
  19. ```

Quiz Options

OptionTypeRequiredDescription
-------------------------------------------------------------------------------------------------------------------------------------------
`choices``array`YesThe
`correctChoice`|YesIndex

↑ back to: Getting Started · Prompts


Survey Prompt


Prompt that allows the user to provide feedback for a list of questions.

Enquirer Survey Prompt


Example Usage

  1. ``` js
  2. const { Survey } = require('enquirer');

  3. const prompt = new Survey({
  4.   name: 'experience',
  5.   message: 'Please rate your experience',
  6.    scale: [
  7.     { name: '1', message: 'Strongly Disagree' },
  8.     { name: '2', message: 'Disagree' },
  9.     { name: '3', message: 'Neutral' },
  10.     { name: '4', message: 'Agree' },
  11.     { name: '5', message: 'Strongly Agree' }
  12.   ],
  13.   margin: [0, 0, 2, 1],
  14.   choices: [
  15.     {
  16.       name: 'interface',
  17.       message: 'The website has a friendly interface.'
  18.     },
  19.     {
  20.       name: 'navigation',
  21.       message: 'The website is easy to navigate.'
  22.     },
  23.     {
  24.       name: 'images',
  25.       message: 'The website usually has good images.'
  26.     },
  27.     {
  28.       name: 'upload',
  29.       message: 'The website makes it easy to upload images.'
  30.     },
  31.     {
  32.       name: 'colors',
  33.       message: 'The website has a pleasing color palette.'
  34.     }
  35.   ]
  36. });

  37. prompt.run()
  38.   .then(value => console.log('ANSWERS:', value))
  39.   .catch(console.error);
  40. ```

Related prompts



Scale Prompt


A more compact version of the Survey prompt, the Scale prompt allows the user to quickly provide feedback using a Likert Scale.

Enquirer Scale Prompt


Example Usage

  1. ``` js
  2. const { Scale } = require('enquirer');
  3. const prompt = new Scale({
  4.   name: 'experience',
  5.   message: 'Please rate your experience',
  6.   scale: [
  7.     { name: '1', message: 'Strongly Disagree' },
  8.     { name: '2', message: 'Disagree' },
  9.     { name: '3', message: 'Neutral' },
  10.     { name: '4', message: 'Agree' },
  11.     { name: '5', message: 'Strongly Agree' }
  12.   ],
  13.   margin: [0, 0, 2, 1],
  14.   choices: [
  15.     {
  16.       name: 'interface',
  17.       message: 'The website has a friendly interface.',
  18.       initial: 2
  19.     },
  20.     {
  21.       name: 'navigation',
  22.       message: 'The website is easy to navigate.',
  23.       initial: 2
  24.     },
  25.     {
  26.       name: 'images',
  27.       message: 'The website usually has good images.',
  28.       initial: 2
  29.     },
  30.     {
  31.       name: 'upload',
  32.       message: 'The website makes it easy to upload images.',
  33.       initial: 2
  34.     },
  35.     {
  36.       name: 'colors',
  37.       message: 'The website has a pleasing color palette.',
  38.       initial: 2
  39.     }
  40.   ]
  41. });

  42. prompt.run()
  43.   .then(value => console.log('ANSWERS:', value))
  44.   .catch(console.error);
  45. ```

Related prompts


↑ back to: Getting Started · Prompts


Select Prompt


Prompt that allows the user to select from a list of options.

Enquirer Select Prompt


Example Usage

  1. ``` js
  2. const { Select } = require('enquirer');

  3. const prompt = new Select({
  4.   name: 'color',
  5.   message: 'Pick a flavor',
  6.   choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange']
  7. });

  8. prompt.run()
  9.   .then(answer => console.log('Answer:', answer))
  10.   .catch(console.error);
  11. ```

Related prompts


↑ back to: Getting Started · Prompts


Sort Prompt


Prompt that allows the user to sort items in a list.

Example

In this example, custom styling is applied to the returned values to make it easier to see what's happening.

Enquirer Sort Prompt


Example Usage

  1. ``` js
  2. const colors = require('ansi-colors');
  3. const { Sort } = require('enquirer');
  4. const prompt = new Sort({
  5.   name: 'colors',
  6.   message: 'Sort the colors in order of preference',
  7.   hint: 'Top is best, bottom is worst',
  8.   numbered: true,
  9.   choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({
  10.     name: n,
  11.     message: colors[n](n)
  12.   }))
  13. });

  14. prompt.run()
  15.   .then(function(answer = []) {
  16.     console.log(answer);
  17.     console.log('Your preferred order of colors is:');
  18.     console.log(answer.map(key => colors[key](key)).join('\n'));
  19.   })
  20.   .catch(console.error);
  21. ```

Related prompts


↑ back to: Getting Started · Prompts


Snippet Prompt


Prompt that allows the user to replace placeholders in a snippet of code or text.

Prompts


Example Usage

  1. ``` js
  2. const semver = require('semver');
  3. const { Snippet } = require('enquirer');
  4. const prompt = new Snippet({
  5.   name: 'username',
  6.   message: 'Fill out the fields in package.json',
  7.   required: true,
  8.   fields: [
  9.     {
  10.       name: 'author_name',
  11.       message: 'Author Name'
  12.     },
  13.     {
  14.       name: 'version',
  15.       validate(value, state, item, index) {
  16.         if (item && item.name === 'version' && !semver.valid(value)) {
  17.           return prompt.styles.danger('version should be a valid semver value');
  18.         }
  19.         return true;
  20.       }
  21.     }
  22.   ],
  23.   template: `{
  24.   "name": "\${name}",
  25.   "description": "\${description}",
  26.   "version": "\${version}",
  27.   "homepage": "https://github.com/\${username}/\${name}",
  28.   "author": "\${author_name} (https://github.com/\${username})",
  29.   "repository": "\${username}/\${name}",
  30.   "license": "\${license:ISC}"
  31. }
  32. `
  33. });

  34. prompt.run()
  35.   .then(answer => console.log('Answer:', answer.result))
  36.   .catch(console.error);
  37. ```

Related prompts


↑ back to: Getting Started · Prompts


Toggle Prompt


Prompt that allows the user to toggle between two values then returns true or false.

Enquirer Toggle Prompt


Example Usage

  1. ``` js
  2. const { Toggle } = require('enquirer');

  3. const prompt = new Toggle({
  4.   message: 'Want to answer?',
  5.   enabled: 'Yep',
  6.   disabled: 'Nope'
  7. });

  8. prompt.run()
  9.   .then(answer => console.log('Answer:', answer))
  10.   .catch(console.error);
  11. ```

Related prompts


↑ back to: Getting Started · Prompts


Prompt Types

There are 5 (soon to be 6!) type classes:
    - Options
    - Properties
    - Methods
    - Choices
    - Related prompts
DatePrompt (Coming Soon!)

Each type is a low-level class that may be used as a starting point for creating higher level prompts. Continue reading to learn how.

ArrayPrompt


The ArrayPrompt class is used for creating prompts that display a list of choices in the terminal. For example, Enquirer uses this class as the basis for the Select and Survey prompts.

Options


In addition to the options available to all prompts, Array prompts also support the following options.

**Option****Required?****Type****Description**
--------------------------------------------------------------------------------------------------------------------------------------------------------------
`autofocus``no``string\|number`The
`stdin``no``stream`The
`stdout``no``stream`The
|

Properties


Array prompts have the following instance properties and getters.

**Property**Type****Description**
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`choices``array`Array
`cursor``number`Position
`enabled``array`Returns
`focused``array`Returns
`focused`Gets
`index``number`Position
`limit``number`The
`selected``array`Either
`visible``string`|

Methods


**Method****Description**
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`pointer()`Returns
`indicator()`Returns
`focus()`Sets

Choices


Array prompts support the choices option, which is the array of choices users will be able to select from when rendered in the terminal.

Type: string|object

Example

  1. ``` js
  2. const { prompt } = require('enquirer');

  3. const questions = [{
  4.   type: 'select',
  5.   name: 'color',
  6.   message: 'Favorite color?',
  7.   initial: 1,
  8.   choices: [
  9.     { name: 'red',   message: 'Red',   value: '#ff0000' }, //<= choice object
  10.     { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object
  11.     { name: 'blue',  message: 'Blue',  value: '#0000ff' }  //<= choice object
  12.   ]
  13. }];

  14. let answers = await prompt(questions);
  15. console.log('Answer:', answers.color);
  16. ```

Defining choices


Whether defined as a string or object, choices are normalized to the following interface:

  1. ``` js
  2. {
  3.   name: string;
  4.   message: string | undefined;
  5.   value: string | undefined;
  6.   hint: string | undefined;
  7.   disabled: boolean | string | undefined;
  8. }
  9. ```

Example

  1. ``` js
  2. const question = {
  3.   name: 'fruit',
  4.   message: 'Favorite fruit?',
  5.   choices: ['Apple', 'Orange', 'Raspberry']
  6. };
  7. ```

Normalizes to the following when the prompt is run:

  1. ``` js
  2. const question = {
  3.   name: 'fruit',
  4.   message: 'Favorite fruit?',
  5.   choices: [
  6.     { name: 'Apple', message: 'Apple', value: 'Apple' },
  7.     { name: 'Orange', message: 'Orange', value: 'Orange' },
  8.     { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' }
  9.   ]
  10. };
  11. ```

Choice properties


The following properties are supported on choice objects.

**Option****Type****Description**
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`name``string`The
`message``string`The
`value``string`Value
`choices``array`Array
`hint``string`Help
`role``string`Determines
`enabled``boolean`Enabled
`disabled``boolean\|string`Disable
`indicator``string\|function`Custom

Related prompts




AuthPrompt


The AuthPrompt is used to create prompts to log in user using any authentication method. For example, Enquirer uses this class as the basis for the BasicAuth Prompt. You can also find prompt examples inexamples/auth/ folder that utilizes AuthPrompt to create OAuth based authentication prompt or a prompt that authenticates using time-based OTP, among others.

AuthPrompt has a factory function that creates an instance of AuthPrompt class and it expects an authenticate function, as an argument, which overrides the authenticate function of the AuthPrompt class.

Methods


**Method****Description**
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`authenticate()`Contain

Choices


Auth prompt supports the choices option, which is the similar to the choices used in Form Prompt.

Example

  1. ``` js
  2. const { AuthPrompt } = require('enquirer');

  3. function authenticate(value, state) {
  4.   if (value.username === this.options.username && value.password === this.options.password) {
  5.     return true;
  6.   }
  7.   return false;
  8. }

  9. const CustomAuthPrompt = AuthPrompt.create(authenticate);

  10. const prompt = new CustomAuthPrompt({
  11.   name: 'password',
  12.   message: 'Please enter your password',
  13.   username: 'rajat-sr',
  14.   password: '1234567',
  15.   choices: [
  16.     { name: 'username', message: 'username' },
  17.     { name: 'password', message: 'password' }
  18.   ]
  19. });

  20. prompt
  21.   .run()
  22.   .then(answer => console.log('Authenticated?', answer))
  23.   .catch(console.error);
  24. ```

Related prompts




BooleanPrompt


The BooleanPrompt class is used for creating prompts that display and return a boolean value.

  1. ``` js
  2. const { BooleanPrompt } = require('enquirer');

  3. const  prompt = new  BooleanPrompt({
  4.   header:  '========================',
  5.   message:  'Do you love enquirer?',
  6.   footer:  '========================',
  7. });

  8. prompt.run()
  9.   .then(answer  =>  console.log('Selected:', answer))
  10.   .catch(console.error);
  11. ```

Returns: boolean


NumberPrompt


The NumberPrompt class is used for creating prompts that display and return a numerical value.

  1. ``` js
  2. const { NumberPrompt } = require('enquirer');

  3. const  prompt = new  NumberPrompt({
  4.   header:  '************************',
  5.   message:  'Input the Numbers:',
  6.   footer:  '************************',
  7. });

  8. prompt.run()
  9.   .then(answer  =>  console.log('Numbers are:', answer))
  10.   .catch(console.error);
  11. ```

Returns: string|number (number, or number formatted as a string)


StringPrompt


The StringPrompt class is used for creating prompts that display and return a string value.

  1. ``` js
  2. const { StringPrompt } = require('enquirer');

  3. const prompt = new StringPrompt({
  4.   header: '************************',
  5.   message: 'Input the String:',
  6.   footer: '************************'
  7. });

  8. prompt.run()
  9.   .then(answer => console.log('String is:', answer))
  10.   .catch(console.error);
  11. ```

Returns: string

❯ Custom prompts

With Enquirer 2.0, custom prompts are easier than ever to create and use.

How do I create a custom prompt?

Custom prompts are created by extending either:
- Enquirer's Prompt class
- one of the built-in prompts, or
- low-level types.



  1. ``` js
  2. const { Prompt } = require('enquirer');

  3. class HaiKarate extends Prompt {
  4.   constructor(options = {}) {
  5.     super(options);
  6.     this.value = options.initial || 0;
  7.     this.cursorHide();
  8.   }
  9.   up() {
  10.     this.value++;
  11.     this.render();
  12.   }
  13.   down() {
  14.     this.value--;
  15.     this.render();
  16.   }
  17.   render() {
  18.     this.clear(); // clear previously rendered prompt from the terminal
  19.     this.write(`${this.state.message}: ${this.value}`);
  20.   }
  21. }

  22. // Use the prompt by creating an instance of your custom prompt class.
  23. const prompt = new HaiKarate({
  24.   message: 'How many sprays do you want?',
  25.   initial: 10
  26. });

  27. prompt.run()
  28.   .then(answer => console.log('Sprays:', answer))
  29.   .catch(console.error);
  30. ```

If you want to be able to specify your prompt by type so that it may be used alongside other prompts, you will need to first create an instance of Enquirer.

  1. ``` js
  2. const Enquirer = require('enquirer');
  3. const enquirer = new Enquirer();
  4. ```

Then use the .register() method to add your custom prompt.

  1. ``` js
  2. enquirer.register('haikarate', HaiKarate);
  3. ```

Now you can do the following when defining "questions".

  1. ``` js
  2. let spritzer = require('cologne-drone');
  3. let answers = await enquirer.prompt([
  4.   {
  5.     type: 'haikarate',
  6.     name: 'cologne',
  7.     message: 'How many sprays do you need?',
  8.     initial: 10,
  9.     async onSubmit(name, value) {
  10.       await spritzer.activate(value); //<= activate drone
  11.       return value;
  12.     }
  13.   }
  14. ]);
  15. ```

❯ Key Bindings

All prompts


These key combinations may be used with all prompts.

**command****description**
----------------------------------------------------------------------
ctrlCancel
ctrlReset

Move cursor


These combinations may be used on prompts that support user input (eg. input prompt, password prompt, and invisible prompt).

**command****description**
----------------------------------------------------------------------
leftMove
rightMove
ctrlMove
ctrlMove
ctrlMove
ctrlMove
ctrlToggle

Edit Input


These key combinations may be used on prompts that support user input (eg. input prompt, password prompt, and invisible prompt).

**command****description**
----------------------------------------------------------------------
ctrlMove
ctrlMove
ctrlMove
ctrlMove
ctrlToggle

**command**command**description**
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
deletebackspaceDelete
fndeleteDelete
optionaltScroll
optionaltScroll

Select choices


These key combinations may be used on prompts that support _multiple_ choices, such as the multiselect prompt, or the select prompt when themultiple options is true.

**command****description**
-------------------------------------------------------------------------------------------------------------------------------------
spaceToggle
numberMove
aToggle
iInvert
gToggle

Hide/show choices


**command****description**
-----------------------------------------------------------------------------
fnDecrease
fnIncrease

Move/lock Pointer


**command****description**
------------------------------------------------------------------------------------------------------------------------------------------------------
numberMove
upMove
downMove
ctrlMove
ctrlMove
shiftScroll
shiftScroll

**command**command**description**
---------------------------------------------------------------------------------------------------------------
fnhomeMove
fnendMove

❯ Release History


Please see CHANGELOG.md.

❯ Performance


System specs


MacBook Pro, Intel Core i7, 2.5 GHz, 16 GB.

Load time


Time it takes for the module to load the first time (average of 3 runs):

  1. ```
  2. enquirer: 4.013ms
  3. inquirer: 286.717ms
  4. ```

❯ About


Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Todo


We're currently working on documentation for the following items. Please star and watch the repository for updates!
[ ] Customizing symbols
[ ] Customizing styles (palette)
[ ] Customizing rendered input
[ ] Customizing returned values
[ ] Customizing key bindings
[ ] Question validation
[ ] Choice validation
[ ] Skipping questions
[ ] Async choices
[ ] Async timers: loaders, spinners and other animations
[ ] Links to examples
Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

  1. ```sh
  2. $ npm install && npm test
  3. ```
  1. ```sh
  2. $ yarn && yarn test
  3. ```

Building docs

_(This project's readme.md is generated by [verb](https://github.com/verbose/v