Back to Enquirer

Enquirer's Prompts

docs/prompts.md

2.4.032.3 KB
Original Source

Enquirer's 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 base Prompt class is used to create all other prompts.

js
const { Prompt } = require('enquirer');
class MyCustomPrompt extends Prompt {}

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:

js
{
  // required
  type: string | function,
  name: string | function,
  message: string | function | async function,

  // optional
  skip: boolean | function | async function,
  initial: string | function | async function,
  format: function | async function,
  result: function | async function,
  validate: function | async function,
}

Each property of the options object is described below:

PropertyRequired?TypeDescription
typeyes`stringfunction`
nameyes`stringfunction`
messageyes`stringfunction`
skipno`booleanfunction`
initialno`stringfunction`
formatnofunctionFunction to format user input in the terminal.
resultnofunctionFunction to format the final submitted value before it's returned.
validatenofunctionFunction to validate the submitted value before it's returned. This function may return a boolean or a string. If a string is returned it will be used as the validation error message.

Example usage

js
const { prompt } = require('enquirer');

const question = {
  type: 'input',
  name: 'username',
  message: 'What is your username?'
};

prompt(question)
  .then(answer => console.log('Answer:', answer))
  .catch(console.error);

Built-in prompts

AutoComplete Prompt

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

<p align="center"> </p>

Example Usage

js
const { AutoComplete } = require('enquirer');

const prompt = new AutoComplete({
  name: 'flavor',
  message: 'Pick your favorite flavor',
  limit: 10,
  initial: 2,
  choices: [
    'Almond',
    'Apple',
    'Banana',
    'Blackberry',
    'Blueberry',
    'Cherry',
    'Chocolate',
    'Cinnamon',
    'Coconut',
    'Cranberry',
    'Grape',
    'Nougat',
    'Orange',
    'Pear',
    'Pineapple',
    'Raspberry',
    'Strawberry',
    'Vanilla',
    'Watermelon',
    'Wintergreen'
  ]
});

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

AutoComplete Options

OptionTypeDefaultDescription
highlightfunctiondim version of primary styleThe color to use when "highlighting" characters in the list that match user input.
multiplebooleanfalseAllow multiple choices to be selected.
suggestfunctionGreedy match, returns choices where choice.message contains the input string.Function that filters choices. Takes user input and a choices array, and returns a list of matching choices.
initialnumber0Preselected item in the list of choices.
footerfunctionNoneFunction that displays footer text

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.

<p align="center"> </p>

Example Usage

js
const { BasicAuth } = require('enquirer');

 const prompt = new BasicAuth({
  name: 'password',
  message: 'Please enter your password',
  username: 'rajat-sr',
  password: '123',
  showPassword: true
});

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

↑ back to: Getting Started · Prompts


Confirm Prompt

Prompt that returns true or false.

<p align="center"> </p>

Example Usage

js
const { Confirm } = require('enquirer');

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

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

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.

<p align="center"> </p>

Example Usage

js
const { Form } = require('enquirer');

const prompt = new Form({
  name: 'user',
  message: 'Please provide the following information:',
  choices: [
    { name: 'firstname', message: 'First Name', initial: 'Jon' },
    { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' },
    { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' }
  ]
});

prompt.run()
  .then(value => console.log('Answer:', value))
  .catch(console.error);

Related prompts

↑ back to: Getting Started · Prompts


Input Prompt

Prompt that takes user input and returns a string.

<p align="center"> </p>

Example Usage

js
const { Input } = require('enquirer');
const prompt = new Input({
  message: 'What is your username?',
  initial: 'jonschlinkert'
});

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

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.

<p align="center"> </p>

Example Usage

js
const { Invisible } = require('enquirer');
const prompt = new Invisible({
  name: 'secret',
  message: 'What is your secret?'
});

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

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.

<p align="center"> </p>

Example Usage

js
const { List } = require('enquirer');
const prompt = new List({
  name: 'keywords',
  message: 'Type comma-separated keywords'
});

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

Related prompts

↑ back to: Getting Started · Prompts


MultiSelect Prompt

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

<p align="center"> </p>

Example Usage

js
const { MultiSelect } = require('enquirer');

const prompt = new MultiSelect({
  name: 'value',
  message: 'Pick your favorite colors',
  limit: 7,
  choices: [
    { name: 'aqua', value: '#00ffff' },
    { name: 'black', value: '#000000' },
    { name: 'blue', value: '#0000ff' },
    { name: 'fuchsia', value: '#ff00ff' },
    { name: 'gray', value: '#808080' },
    { name: 'green', value: '#008000' },
    { name: 'lime', value: '#00ff00' },
    { name: 'maroon', value: '#800000' },
    { name: 'navy', value: '#000080' },
    { name: 'olive', value: '#808000' },
    { name: 'purple', value: '#800080' },
    { name: 'red', value: '#ff0000' },
    { name: 'silver', value: '#c0c0c0' },
    { name: 'teal', value: '#008080' },
    { name: 'white', value: '#ffffff' },
    { name: 'yellow', value: '#ffff00' }
  ]
});

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

// Answer: ['aqua', 'blue', 'fuchsia']

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

js
const { MultiSelect } = require('enquirer');

const prompt = new MultiSelect({
  name: 'value',
  message: 'Pick your favorite colors',
  limit: 7,
  choices: [
    { name: 'aqua', value: '#00ffff' },
    { name: 'black', value: '#000000' },
    { name: 'blue', value: '#0000ff' },
    { name: 'fuchsia', value: '#ff00ff' },
    { name: 'gray', value: '#808080' },
    { name: 'green', value: '#008000' },
    { name: 'lime', value: '#00ff00' },
    { name: 'maroon', value: '#800000' },
    { name: 'navy', value: '#000080' },
    { name: 'olive', value: '#808000' },
    { name: 'purple', value: '#800080' },
    { name: 'red', value: '#ff0000' },
    { name: 'silver', value: '#c0c0c0' },
    { name: 'teal', value: '#008080' },
    { name: 'white', value: '#ffffff' },
    { name: 'yellow', value: '#ffff00' }
  ],
  result(names) {
   return this.map(names);
  }
});

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

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

Example alternate labels

js
const { MultiSelect } = require('enquirer');

const prompt = new MultiSelect({
  name: 'color',
  message: 'Pick a flavor',
  choices: [
    { message: 'Negative Red', name: 'cyan', value: '#00ffff' },
    { message: 'Lights Out', name: 'black', value: '#000000' },
    { message: 'The Ocean', name: 'blue', value: '#0000ff' },
  ]
});

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

Related prompts

↑ back to: Getting Started · Prompts


Numeral Prompt

Prompt that takes a number as input.

<p align="center"> </p>

Example Usage

js
const { NumberPrompt } = require('enquirer');

const prompt = new NumberPrompt({
  name: 'number',
  message: 'Please enter a number'
});

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

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

<p align="center"> </p>

Example Usage

js
const { Password } = require('enquirer');

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

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

Related prompts

↑ back to: Getting Started · Prompts


Quiz Prompt

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

<p align="center"> </p>

Example Usage

js
const { Quiz } = require('enquirer');

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

 prompt
  .run()
  .then(answer => {
    if (answer.correct) {
      console.log('Correct!');
    } else {
      console.log(`Wrong! Correct answer is ${answer.correctAnswer}`);
    }
  })
  .catch(console.error);

Quiz Options

OptionTypeRequiredDescription
choicesarrayYesThe list of possible answers to the quiz question.
correctChoicenumberYesIndex of the correct choice from the choices array.

↑ back to: Getting Started · Prompts


Survey Prompt

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

<p align="center"> </p>

Example Usage

js
const { Survey } = require('enquirer');

const prompt = new Survey({
  name: 'experience',
  message: 'Please rate your experience',
   scale: [
    { name: '1', message: 'Strongly Disagree' },
    { name: '2', message: 'Disagree' },
    { name: '3', message: 'Neutral' },
    { name: '4', message: 'Agree' },
    { name: '5', message: 'Strongly Agree' }
  ],
  margin: [0, 0, 2, 1],
  choices: [
    {
      name: 'interface',
      message: 'The website has a friendly interface.'
    },
    {
      name: 'navigation',
      message: 'The website is easy to navigate.'
    },
    {
      name: 'images',
      message: 'The website usually has good images.'
    },
    {
      name: 'upload',
      message: 'The website makes it easy to upload images.'
    },
    {
      name: 'colors',
      message: 'The website has a pleasing color palette.'
    }
  ]
});

prompt.run()
  .then(value => console.log('ANSWERS:', value))
  .catch(console.error);

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.

<p align="center"> </p>

Example Usage

js
const { Scale } = require('enquirer');
const prompt = new Scale({
  name: 'experience',
  message: 'Please rate your experience',
  scale: [
    { name: '1', message: 'Strongly Disagree' },
    { name: '2', message: 'Disagree' },
    { name: '3', message: 'Neutral' },
    { name: '4', message: 'Agree' },
    { name: '5', message: 'Strongly Agree' }
  ],
  margin: [0, 0, 2, 1],
  choices: [
    {
      name: 'interface',
      message: 'The website has a friendly interface.',
      initial: 2
    },
    {
      name: 'navigation',
      message: 'The website is easy to navigate.',
      initial: 2
    },
    {
      name: 'images',
      message: 'The website usually has good images.',
      initial: 2
    },
    {
      name: 'upload',
      message: 'The website makes it easy to upload images.',
      initial: 2
    },
    {
      name: 'colors',
      message: 'The website has a pleasing color palette.',
      initial: 2
    }
  ]
});

prompt.run()
  .then(value => console.log('ANSWERS:', value))
  .catch(console.error);

Related prompts

↑ back to: Getting Started · Prompts


Select Prompt

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

<p align="center"> </p>

Example Usage

js
const { Select } = require('enquirer');

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

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

Example key-value pairs

js
const { Select } = require('enquirer');

const prompt = new Select({
  name: 'color',
  message: 'Pick a color',
  choices: [
    { name: 'cyan', value: '#00ffff' },
    { name: 'black', value: '#000000' },
    { name: 'blue', value: '#0000ff' },
  ]
});

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

Example alternate labels

js
const { Select } = require('enquirer');

const prompt = new Select({
  name: 'color',
  message: 'Pick a color',
  choices: [
    { message: 'Negative Red', name: 'cyan', value: '#00ffff' },
    { message: 'Lights Out', name: 'black', value: '#000000' },
    { message: 'The Ocean', name: 'blue', value: '#0000ff' },
  ]
});

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

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.

<p align="center"> </p>

Example Usage

js
const colors = require('ansi-colors');
const { Sort } = require('enquirer');
const prompt = new Sort({
  name: 'colors',
  message: 'Sort the colors in order of preference',
  hint: 'Top is best, bottom is worst',
  numbered: true,
  choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({
    name: n,
    message: colors[n](n)
  }))
});

prompt.run()
  .then(function(answer = []) {
    console.log(answer);
    console.log('Your preferred order of colors is:');
    console.log(answer.map(key => colors[key](key)).join('\n'));
  })
  .catch(console.error);

Related prompts

↑ back to: Getting Started · Prompts


Snippet Prompt

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

<p align="center"> </p>

Example Usage

js
const semver = require('semver');
const { Snippet } = require('enquirer');
const prompt = new Snippet({
  name: 'username',
  message: 'Fill out the fields in package.json',
  required: true,
  fields: [
    {
      name: 'author_name',
      message: 'Author Name'
    },
    {
      name: 'version',
      validate(value, state, item, index) {
        if (item && item.name === 'version' && !semver.valid(value)) {
          return prompt.styles.danger('version should be a valid semver value');
        }
        return true;
      }
    }
  ],
  template: `{
  "name": "\${name}",
  "description": "\${description}",
  "version": "\${version}",
  "homepage": "https://github.com/\${username}/\${name}",
  "author": "\${author_name} (https://github.com/\${username})",
  "repository": "\${username}/\${name}",
  "license": "\${license:ISC}"
}
`
});

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

Related prompts

↑ back to: Getting Started · Prompts


Toggle Prompt

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

<p align="center"> </p>

Example Usage

js
const { Toggle } = require('enquirer');

const prompt = new Toggle({
  message: 'Want to answer?',
  enabled: 'Yep',
  disabled: 'Nope'
});

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

Related prompts

↑ back to: Getting Started · Prompts


Prompt Types

There are 5 (soon to be 6!) type classes:

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.

OptionRequired?TypeDescription
autofocusno`stringnumber`
stdinnostreamThe input stream to use for emitting keypress events. Defaults to process.stdin.
stdoutnostreamThe output stream to use for writing the prompt to the terminal. Defaults to process.stdout.

Properties

Array prompts have the following instance properties and getters.

Property nameTypeDescription
choicesarrayArray of choices that have been normalized from choices passed on the prompt options.
cursornumberPosition of the cursor relative to the user input (string).
enabledarrayReturns an array of enabled choices.
focusedarrayReturns the currently selected choice in the visible list of choices. This is similar to the concept of focus in HTML and CSS. Focused choices are always visible (on-screen). When a list of choices is longer than the list of visible choices, and an off-screen choice is focused, the list will scroll to the focused choice and re-render.
focusedGets the currently selected choice. Equivalent to prompt.choices[prompt.index].
indexnumberPosition of the pointer in the visible list (array) of choices.
limitnumberThe number of choices to display on-screen.
selectedarrayEither a list of enabled choices (when options.multiple is true) or the currently focused choice.
visiblestring

Methods

MethodDescription
pointer()Returns the visual symbol to use to identify the choice that currently has focus. The symbol is often used for this. The pointer is not always visible, as with the autocomplete prompt.
indicator()Returns the visual symbol that indicates whether or not a choice is checked/enabled.
focus()Sets focus on a choice, if it can be focused.

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

js
const { prompt } = require('enquirer');

const questions = [{
  type: 'select',
  name: 'color',
  message: 'Favorite color?',
  initial: 1,
  choices: [
    { name: 'red',   message: 'Red',   value: '#ff0000' }, //<= choice object
    { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object
    { name: 'blue',  message: 'Blue',  value: '#0000ff' }  //<= choice object
  ]
}];

const answers = await prompt(questions);
console.log('Answer:', answers.color);

Defining choices

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

js
{
  name: string;
  message: string | undefined;
  value: string | undefined;
  hint: string | undefined;
  disabled: boolean | string | undefined;
}

Example

js
const question = {
  name: 'fruit',
  message: 'Favorite fruit?',
  choices: ['Apple', 'Orange', 'Raspberry']
};

Normalizes to the following when the prompt is run:

js
const question = {
  name: 'fruit',
  message: 'Favorite fruit?',
  choices: [
    { name: 'Apple', message: 'Apple', value: 'Apple' },
    { name: 'Orange', message: 'Orange', value: 'Orange' },
    { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' }
  ]
};

Choice properties

The following properties are supported on choice objects.

OptionTypeDescription
namestringThe unique key to identify a choice
messagestringThe message to display in the terminal. name is used when this is undefined.
valuestringValue to associate with the choice. Useful for creating key-value pairs from user choices. name is used when this is undefined.
choicesarrayArray of "child" choices.
hintstringHelp message to display next to a choice.
rolestringDetermines how the choice will be displayed. Currently the only role supported is separator. Additional roles may be added in the future (like heading, etc). Please create a [feature request]
enabledbooleanEnabled a choice by default. This is only supported when options.multiple is true or on prompts that support multiple choices, like MultiSelect.
disabled`booleanstring`
indicator`stringfunction`

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 in examples/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

MethodDescription
authenticate()Contain all the authentication logic. This function should be overridden to implement custom authentication logic. The default authenticate function throws an error if no other function is provided.

Choices

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

Example

js
const { AuthPrompt } = require('enquirer');

function authenticate(value, state) {
  if (value.username === this.options.username && value.password === this.options.password) {
    return true;
  }
  return false;
}

const CustomAuthPrompt = AuthPrompt.create(authenticate);

const prompt = new CustomAuthPrompt({
  name: 'password',
  message: 'Please enter your password',
  username: 'rajat-sr',
  password: '1234567',
  choices: [
    { name: 'username', message: 'username' },
    { name: 'password', message: 'password' }
  ]
});

prompt
  .run()
  .then(answer => console.log('Authenticated?', answer))
  .catch(console.error);

BooleanPrompt

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

js
const { BooleanPrompt } = require('enquirer');

const  prompt = new  BooleanPrompt({
  header:  '========================',
  message:  'Do you love enquirer?',
  footer:  '========================',
});

prompt.run()
  .then(answer  =>  console.log('Selected:', answer))
  .catch(console.error);

Returns: boolean


NumberPrompt

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

js
const { NumberPrompt } = require('enquirer');

const  prompt = new  NumberPrompt({
  header:  '************************',
  message:  'Input the Numbers:',
  footer:  '************************',
});

prompt.run()
  .then(answer  =>  console.log('Numbers are:', answer))
  .catch(console.error);

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.

js
const { StringPrompt } = require('enquirer');

const prompt = new StringPrompt({
  header: '************************',
  message: 'Input the String:',
  footer: '************************'
});

prompt.run()
  .then(answer => console.log('String is:', answer))
  .catch(console.error);

Returns: string

❯ Custom prompts

{%= format(include('docs/custom-prompts.md')) %}