1 <h1 align="center">Enquirer</h1>
4 <a href="https://npmjs.org/package/enquirer">
5 <img src="https://img.shields.io/npm/v/enquirer.svg" alt="version">
7 <a href="https://travis-ci.org/enquirer/enquirer">
8 <img src="https://img.shields.io/travis/enquirer/enquirer.svg" alt="travis">
10 <a href="https://npmjs.org/package/enquirer">
11 <img src="https://img.shields.io/npm/dm/enquirer.svg" alt="downloads">
19 <b>Stylish CLI prompts that are user-friendly, intuitive and easy to create.</b><br>
20 <sub>>_ Prompts should be more like conversations than inquisitions▌</sub>
26 <sub>(Example shows Enquirer's <a href="#survey-prompt">Survey Prompt</a>)</a></sub>
27 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"><br>
28 <sub>The terminal in all examples is <a href="https://hyper.is/">Hyper</a>, theme is <a href="https://github.com/jonschlinkert/hyper-monokai-extended">hyper-monokai-extended</a>.</sub><br><br>
29 <a href="#built-in-prompts"><strong>See more prompt examples</strong></a>
35 Created by [jonschlinkert](https://github.com/jonschlinkert) and [doowb](https://github.com/doowb), 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.
37 * **Fast** - [Loads in ~4ms](#-performance) (that's about _3-4 times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps_)
38 * **Lightweight** - Only one dependency, the excellent [ansi-colors](https://github.com/doowb/ansi-colors) by [Brian Woodward](https://github.com/doowb).
39 * **Easy to implement** - Uses promises and async/await and sensible defaults to make prompts easy to create and implement.
40 * **Easy to use** - Thrill your users with a better experience! Navigating around input and choices is a breeze. You can even create [quizzes](examples/fun/countdown.js), or [record](examples/fun/record.js) and [playback](examples/fun/play.js) key bindings to aid with tutorials and videos.
41 * **Intuitive** - Keypress combos are available to simplify usage.
42 * **Flexible** - All prompts can be used standalone or chained together.
43 * **Stylish** - Easily override semantic styles and symbols for any part of the prompt.
44 * **Extensible** - Easily create and use custom prompts by extending Enquirer's built-in [prompts](#-prompts).
45 * **Pluggable** - Add advanced features to Enquirer using plugins.
46 * **Validation** - Optionally validate user input with any prompt.
47 * **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.
48 * **Examples** - There are numerous [examples](examples) available to help you get started.
50 If you like Enquirer, please consider starring or tweeting about this project to show your support. Thanks!
55 <b>>_ Ready to start making prompts your users will love? ▌</b><br>
56 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/heartbeat.gif" alt="Enquirer Select Prompt with heartbeat example" width="750">
64 Get started with Enquirer, the most powerful and easy-to-use Node.js library for creating interactive CLI prompts.
66 * [Install](#-install)
68 * [Enquirer](#-enquirer)
69 * [Prompts](#-prompts)
70 - [Built-in Prompts](#-prompts)
71 - [Custom Prompts](#-custom-prompts)
72 * [Key Bindings](#-key-bindings)
73 * [Options](#-options)
74 * [Release History](#-release-history)
75 * [Performance](#-performance)
82 Install with [npm](https://www.npmjs.com/):
85 $ npm install enquirer --save
87 Install with [yarn](https://yarnpkg.com/en/):
94 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/npm-install.gif" alt="Install Enquirer with NPM" width="750">
97 _(Requires Node.js 8.6 or higher. Please let us know if you need support for an earlier version by creating an [issue](../../issues/new).)_
105 The easiest way to get started with enquirer is to pass a [question object](#prompt-options) to the `prompt` method.
108 const { prompt } = require('enquirer');
110 const response = await prompt({
113 message: 'What is your username?'
116 console.log(response); // { username: 'jonschlinkert' }
119 _(Examples with `await` need to be run inside an `async` function)_
123 Pass an array of ["question" objects](#prompt-options) to run a series of prompts.
126 const response = await prompt([
130 message: 'What is your name?'
135 message: 'What is your username?'
139 console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' }
142 ### Different ways to run enquirer
144 #### 1. By importing the specific `built-in prompt`
147 const { Confirm } = require('enquirer');
149 const prompt = new Confirm({
151 message: 'Did you like enquirer?'
155 .then(answer => console.log('Answer:', answer));
158 #### 2. By passing the options to `prompt`
161 const { prompt } = require('enquirer');
166 message: 'Did you like enquirer?'
168 .then(answer => console.log('Answer:', answer));
171 **Jump to**: [Getting Started](#-getting-started) · [Prompts](#-prompts) · [Options](#-options) · [Key Bindings](#-key-bindings)
177 **Enquirer is a prompt runner**
179 Add Enquirer to your JavaScript project with following line of code.
182 const Enquirer = require('enquirer');
185 The main export of this library is the `Enquirer` class, which has methods and features designed to simplify running prompts.
188 const { prompt } = require('enquirer');
193 message: 'What is your username?'
198 message: 'What is your password?'
202 let answers = await prompt(question);
203 console.log(answers);
206 **Prompts control how values are rendered and returned**
208 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.
210 **How can I customize prompts?**
212 Below in this guide you will find information about creating [custom prompts](#-custom-prompts). For now, we'll focus on how to customize an existing prompt.
214 All of the individual [prompt classes](#built-in-prompts) in this library are exposed as static properties on Enquirer. This allows them to be used directly without using `enquirer.prompt()`.
216 Use this approach if you need to modify a prompt instance, or listen for events on the prompt.
221 const { Input } = require('enquirer');
222 const prompt = new Input({
224 message: 'What is your username?'
228 .then(answer => console.log('Username:', answer))
229 .catch(console.error);
232 ### [Enquirer](index.js#L20)
234 Create an instance of `Enquirer`.
238 * `options` **{Object}**: (optional) Options to use with all prompts.
239 * `answers` **{Object}**: (optional) Answers object to initialize with.
244 const Enquirer = require('enquirer');
245 const enquirer = new Enquirer();
248 ### [register()](index.js#L42)
250 Register a custom prompt type.
254 * `type` **{String}**
255 * `fn` **{Function|Prompt}**: `Prompt` class, or a function that returns a `Prompt` class.
256 * `returns` **{Object}**: Returns the Enquirer instance
261 const Enquirer = require('enquirer');
262 const enquirer = new Enquirer();
263 enquirer.register('customType', require('./custom-prompt'));
266 ### [prompt()](index.js#L78)
268 Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user.
272 * `questions` **{Array|Object}**: Options objects for one or more prompts to run.
273 * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses.
278 const Enquirer = require('enquirer');
279 const enquirer = new Enquirer();
281 const response = await enquirer.prompt({
284 message: 'What is your username?'
286 console.log(response);
289 ### [use()](index.js#L160)
291 Use an enquirer plugin.
295 * `plugin` **{Function}**: Plugin function that takes an instance of Enquirer.
296 * `returns` **{Object}**: Returns the Enquirer instance.
301 const Enquirer = require('enquirer');
302 const enquirer = new Enquirer();
303 const plugin = enquirer => {
304 // do stuff to enquire instance
306 enquirer.use(plugin);
309 ### [Enquirer#prompt](index.js#L210)
311 Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user.
315 * `questions` **{Array|Object}**: Options objects for one or more prompts to run.
316 * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses.
321 const { prompt } = require('enquirer');
322 const response = await prompt({
325 message: 'What is your username?'
327 console.log(response);
334 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.
336 **Getting started with Enquirer's prompts**
338 * [Prompt](#prompt) - The base `Prompt` class used by other prompts
339 - [Prompt Options](#prompt-options)
340 * [Built-in prompts](#built-in-prompts)
341 * [Prompt Types](#prompt-types) - The base `Prompt` class used by other prompts
342 * [Custom prompts](#%E2%9D%AF-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.
346 The base `Prompt` class is used to create all other prompts.
349 const { Prompt } = require('enquirer');
350 class MyCustomPrompt extends Prompt {}
353 See the documentation for [creating custom prompts](#-custom-prompts) to learn more about how this works.
357 Each prompt takes an options object (aka "question" object), that implements the following interface:
362 type: string | function,
363 name: string | function,
364 message: string | function | async function,
367 skip: boolean | function | async function,
368 initial: string | function | async function,
369 format: function | async function,
370 result: function | async function,
371 validate: function | async function,
374 Each property of the options object is described below:
376 | **Property** | **Required?** | **Type** | **Description** |
377 | ------------ | ------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
378 | `type` | yes | `string\|function` | Enquirer uses this value to determine the type of prompt to run, but it's optional when prompts are run directly. |
379 | `name` | yes | `string\|function` | Used as the key for the answer on the returned values (answers) object. |
380 | `message` | yes | `string\|function` | The message to display when the prompt is rendered in the terminal. |
381 | `skip` | no | `boolean\|function` | If `true` it will not ask that prompt. |
382 | `initial` | no | `string\|function` | The default value to return if the user does not supply a value. |
383 | `format` | no | `function` | Function to format user input in the terminal. |
384 | `result` | no | `function` | Function to format the final submitted value before it's returned. |
385 | `validate` | no | `function` | Function 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. |
390 const { prompt } = require('enquirer');
395 message: 'What is your username?'
399 .then(answer => console.log('Answer:', answer))
400 .catch(console.error);
407 * [AutoComplete Prompt](#autocomplete-prompt)
408 * [BasicAuth Prompt](#basicauth-prompt)
409 * [Confirm Prompt](#confirm-prompt)
410 * [Form Prompt](#form-prompt)
411 * [Input Prompt](#input-prompt)
412 * [Invisible Prompt](#invisible-prompt)
413 * [List Prompt](#list-prompt)
414 * [MultiSelect Prompt](#multiselect-prompt)
415 * [Numeral Prompt](#numeral-prompt)
416 * [Password Prompt](#password-prompt)
417 * [Quiz Prompt](#quiz-prompt)
418 * [Survey Prompt](#survey-prompt)
419 * [Scale Prompt](#scale-prompt)
420 * [Select Prompt](#select-prompt)
421 * [Sort Prompt](#sort-prompt)
422 * [Snippet Prompt](#snippet-prompt)
423 * [Toggle Prompt](#toggle-prompt)
425 ### AutoComplete Prompt
427 Prompt that auto-completes as the user types, and returns the selected value as a string.
430 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/autocomplete-prompt.gif" alt="Enquirer AutoComplete Prompt" width="750">
436 const { AutoComplete } = require('enquirer');
438 const prompt = new AutoComplete({
440 message: 'Pick your favorite flavor',
468 .then(answer => console.log('Answer:', answer))
469 .catch(console.error);
472 **AutoComplete Options**
474 | Option | Type | Default | Description |
475 | ----------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
476 | `highlight` | `function` | `dim` version of primary style | The color to use when "highlighting" characters in the list that match user input. |
477 | `multiple` | `boolean` | `false` | Allow multiple choices to be selected. |
478 | `suggest` | `function` | Greedy match, returns true if choice message contains input string. | Function that filters choices. Takes user input and a choices array, and returns a list of matching choices. |
479 | `initial` | `number` | 0 | Preselected item in the list of choices. |
480 | `footer` | `function` | None | Function that displays [footer text](https://github.com/enquirer/enquirer/blob/6c2819518a1e2ed284242a99a685655fbaabfa28/examples/autocomplete/option-footer.js#L10) |
484 * [Select](#select-prompt)
485 * [MultiSelect](#multiselect-prompt)
486 * [Survey](#survey-prompt)
488 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
494 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.
497 <img src="https://user-images.githubusercontent.com/13731210/61570485-7ffd9c00-aaaa-11e9-857a-d47dc7008284.gif" alt="Enquirer BasicAuth Prompt" width="750">
503 const { BasicAuth } = require('enquirer');
505 const prompt = new BasicAuth({
507 message: 'Please enter your password',
508 username: 'rajat-sr',
515 .then(answer => console.log('Answer:', answer))
516 .catch(console.error);
519 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
525 Prompt that returns `true` or `false`.
528 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/confirm-prompt.gif" alt="Enquirer Confirm Prompt" width="750">
534 const { Confirm } = require('enquirer');
536 const prompt = new Confirm({
538 message: 'Want to answer?'
542 .then(answer => console.log('Answer:', answer))
543 .catch(console.error);
548 * [Input](#input-prompt)
549 * [Numeral](#numeral-prompt)
550 * [Password](#password-prompt)
552 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
558 Prompt that allows the user to enter and submit multiple values on a single terminal screen.
561 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/form-prompt.gif" alt="Enquirer Form Prompt" width="750">
567 const { Form } = require('enquirer');
569 const prompt = new Form({
571 message: 'Please provide the following information:',
573 { name: 'firstname', message: 'First Name', initial: 'Jon' },
574 { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' },
575 { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' }
580 .then(value => console.log('Answer:', value))
581 .catch(console.error);
586 * [Input](#input-prompt)
587 * [Survey](#survey-prompt)
589 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
595 Prompt that takes user input and returns a string.
598 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/input-prompt.gif" alt="Enquirer Input Prompt" width="750">
604 const { Input } = require('enquirer');
605 const prompt = new Input({
606 message: 'What is your username?',
607 initial: 'jonschlinkert'
611 .then(answer => console.log('Answer:', answer))
615 You can use [data-store](https://github.com/jonschlinkert/data-store) to store [input history](https://github.com/enquirer/enquirer/blob/master/examples/input/option-history.js) that the user can cycle through (see [source](https://github.com/enquirer/enquirer/blob/8407dc3579123df5e6e20215078e33bb605b0c37/lib/prompts/input.js)).
619 * [Confirm](#confirm-prompt)
620 * [Numeral](#numeral-prompt)
621 * [Password](#password-prompt)
623 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
629 Prompt that takes user input, hides it from the terminal, and returns a string.
632 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/invisible-prompt.gif" alt="Enquirer Invisible Prompt" width="750">
638 const { Invisible } = require('enquirer');
639 const prompt = new Invisible({
641 message: 'What is your secret?'
645 .then(answer => console.log('Answer:', { secret: answer }))
646 .catch(console.error);
651 * [Password](#password-prompt)
652 * [Input](#input-prompt)
654 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
660 Prompt that returns a list of values, created by splitting the user input. The default split character is `,` with optional trailing whitespace.
663 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/list-prompt.gif" alt="Enquirer List Prompt" width="750">
669 const { List } = require('enquirer');
670 const prompt = new List({
672 message: 'Type comma-separated keywords'
676 .then(answer => console.log('Answer:', answer))
677 .catch(console.error);
682 * [Sort](#sort-prompt)
683 * [Select](#select-prompt)
685 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
689 ### MultiSelect Prompt
691 Prompt that allows the user to select multiple items from a list of options.
694 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/multiselect-prompt.gif" alt="Enquirer MultiSelect Prompt" width="750">
700 const { MultiSelect } = require('enquirer');
702 const prompt = new MultiSelect({
704 message: 'Pick your favorite colors',
707 { name: 'aqua', value: '#00ffff' },
708 { name: 'black', value: '#000000' },
709 { name: 'blue', value: '#0000ff' },
710 { name: 'fuchsia', value: '#ff00ff' },
711 { name: 'gray', value: '#808080' },
712 { name: 'green', value: '#008000' },
713 { name: 'lime', value: '#00ff00' },
714 { name: 'maroon', value: '#800000' },
715 { name: 'navy', value: '#000080' },
716 { name: 'olive', value: '#808000' },
717 { name: 'purple', value: '#800080' },
718 { name: 'red', value: '#ff0000' },
719 { name: 'silver', value: '#c0c0c0' },
720 { name: 'teal', value: '#008080' },
721 { name: 'white', value: '#ffffff' },
722 { name: 'yellow', value: '#ffff00' }
727 .then(answer => console.log('Answer:', answer))
728 .catch(console.error);
730 // Answer: ['aqua', 'blue', 'fuchsia']
733 **Example key-value pairs**
735 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](./examples/multiselect/option-result.js)
738 const { MultiSelect } = require('enquirer');
740 const prompt = new MultiSelect({
742 message: 'Pick your favorite colors',
745 { name: 'aqua', value: '#00ffff' },
746 { name: 'black', value: '#000000' },
747 { name: 'blue', value: '#0000ff' },
748 { name: 'fuchsia', value: '#ff00ff' },
749 { name: 'gray', value: '#808080' },
750 { name: 'green', value: '#008000' },
751 { name: 'lime', value: '#00ff00' },
752 { name: 'maroon', value: '#800000' },
753 { name: 'navy', value: '#000080' },
754 { name: 'olive', value: '#808000' },
755 { name: 'purple', value: '#800080' },
756 { name: 'red', value: '#ff0000' },
757 { name: 'silver', value: '#c0c0c0' },
758 { name: 'teal', value: '#008080' },
759 { name: 'white', value: '#ffffff' },
760 { name: 'yellow', value: '#ffff00' }
763 return this.map(names);
768 .then(answer => console.log('Answer:', answer))
769 .catch(console.error);
771 // Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' }
776 * [AutoComplete](#autocomplete-prompt)
777 * [Select](#select-prompt)
778 * [Survey](#survey-prompt)
780 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
786 Prompt that takes a number as input.
789 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/numeral-prompt.gif" alt="Enquirer Numeral Prompt" width="750">
795 const { NumberPrompt } = require('enquirer');
797 const prompt = new NumberPrompt({
799 message: 'Please enter a number'
803 .then(answer => console.log('Answer:', answer))
804 .catch(console.error);
809 * [Input](#input-prompt)
810 * [Confirm](#confirm-prompt)
812 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
818 Prompt that takes user input and masks it in the terminal. Also see the [invisible prompt](#invisible-prompt)
821 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/password-prompt.gif" alt="Enquirer Password Prompt" width="750">
827 const { Password } = require('enquirer');
829 const prompt = new Password({
831 message: 'What is your password?'
835 .then(answer => console.log('Answer:', answer))
836 .catch(console.error);
841 * [Input](#input-prompt)
842 * [Invisible](#invisible-prompt)
844 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
850 Prompt that allows the user to play multiple-choice quiz questions.
853 <img src="https://user-images.githubusercontent.com/13731210/61567561-891d4780-aa6f-11e9-9b09-3d504abd24ed.gif" alt="Enquirer Quiz Prompt" width="750">
859 const { Quiz } = require('enquirer');
861 const prompt = new Quiz({
863 message: 'How many countries are there in the world?',
864 choices: ['165', '175', '185', '195', '205'],
871 if (answer.correct) {
872 console.log('Correct!');
874 console.log(`Wrong! Correct answer is ${answer.correctAnswer}`);
877 .catch(console.error);
882 | Option | Type | Required | Description |
883 | ----------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------ |
884 | `choices` | `array` | Yes | The list of possible answers to the quiz question. |
885 | `correctChoice`| `number` | Yes | Index of the correct choice from the `choices` array. |
887 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
893 Prompt that allows the user to provide feedback for a list of questions.
896 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750">
902 const { Survey } = require('enquirer');
904 const prompt = new Survey({
906 message: 'Please rate your experience',
908 { name: '1', message: 'Strongly Disagree' },
909 { name: '2', message: 'Disagree' },
910 { name: '3', message: 'Neutral' },
911 { name: '4', message: 'Agree' },
912 { name: '5', message: 'Strongly Agree' }
914 margin: [0, 0, 2, 1],
918 message: 'The website has a friendly interface.'
922 message: 'The website is easy to navigate.'
926 message: 'The website usually has good images.'
930 message: 'The website makes it easy to upload images.'
934 message: 'The website has a pleasing color palette.'
940 .then(value => console.log('ANSWERS:', value))
941 .catch(console.error);
946 * [Scale](#scale-prompt)
947 * [Snippet](#snippet-prompt)
948 * [Select](#select-prompt)
954 A more compact version of the [Survey prompt](#survey-prompt), the Scale prompt allows the user to quickly provide feedback using a [Likert Scale](https://en.wikipedia.org/wiki/Likert_scale).
957 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/scale-prompt.gif" alt="Enquirer Scale Prompt" width="750">
963 const { Scale } = require('enquirer');
964 const prompt = new Scale({
966 message: 'Please rate your experience',
968 { name: '1', message: 'Strongly Disagree' },
969 { name: '2', message: 'Disagree' },
970 { name: '3', message: 'Neutral' },
971 { name: '4', message: 'Agree' },
972 { name: '5', message: 'Strongly Agree' }
974 margin: [0, 0, 2, 1],
978 message: 'The website has a friendly interface.',
983 message: 'The website is easy to navigate.',
988 message: 'The website usually has good images.',
993 message: 'The website makes it easy to upload images.',
998 message: 'The website has a pleasing color palette.',
1005 .then(value => console.log('ANSWERS:', value))
1006 .catch(console.error);
1011 * [AutoComplete](#autocomplete-prompt)
1012 * [Select](#select-prompt)
1013 * [Survey](#survey-prompt)
1015 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
1021 Prompt that allows the user to select from a list of options.
1024 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/select-prompt.gif" alt="Enquirer Select Prompt" width="750">
1030 const { Select } = require('enquirer');
1032 const prompt = new Select({
1034 message: 'Pick a flavor',
1035 choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange']
1039 .then(answer => console.log('Answer:', answer))
1040 .catch(console.error);
1045 * [AutoComplete](#autocomplete-prompt)
1046 * [MultiSelect](#multiselect-prompt)
1048 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
1054 Prompt that allows the user to sort items in a list.
1058 In this [example](https://github.com/enquirer/enquirer/raw/master/examples/sort/prompt.js), custom styling is applied to the returned values to make it easier to see what's happening.
1061 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/sort-prompt.gif" alt="Enquirer Sort Prompt" width="750">
1067 const colors = require('ansi-colors');
1068 const { Sort } = require('enquirer');
1069 const prompt = new Sort({
1071 message: 'Sort the colors in order of preference',
1072 hint: 'Top is best, bottom is worst',
1074 choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({
1076 message: colors[n](n)
1081 .then(function(answer = []) {
1082 console.log(answer);
1083 console.log('Your preferred order of colors is:');
1084 console.log(answer.map(key => colors[key](key)).join('\n'));
1086 .catch(console.error);
1091 * [List](#list-prompt)
1092 * [Select](#select-prompt)
1094 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
1100 Prompt that allows the user to replace placeholders in a snippet of code or text.
1103 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/snippet-prompt.gif" alt="Prompts" width="750">
1109 const semver = require('semver');
1110 const { Snippet } = require('enquirer');
1111 const prompt = new Snippet({
1113 message: 'Fill out the fields in package.json',
1117 name: 'author_name',
1118 message: 'Author Name'
1122 validate(value, state, item, index) {
1123 if (item && item.name === 'version' && !semver.valid(value)) {
1124 return prompt.styles.danger('version should be a valid semver value');
1132 "description": "\${description}",
1133 "version": "\${version}",
1134 "homepage": "https://github.com/\${username}/\${name}",
1135 "author": "\${author_name} (https://github.com/\${username})",
1136 "repository": "\${username}/\${name}",
1137 "license": "\${license:ISC}"
1143 .then(answer => console.log('Answer:', answer.result))
1144 .catch(console.error);
1149 * [Survey](#survey-prompt)
1150 * [AutoComplete](#autocomplete-prompt)
1152 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
1158 Prompt that allows the user to toggle between two values then returns `true` or `false`.
1161 <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/toggle-prompt.gif" alt="Enquirer Toggle Prompt" width="750">
1167 const { Toggle } = require('enquirer');
1169 const prompt = new Toggle({
1170 message: 'Want to answer?',
1176 .then(answer => console.log('Answer:', answer))
1177 .catch(console.error);
1182 * [Confirm](#confirm-prompt)
1183 * [Input](#input-prompt)
1184 * [Sort](#sort-prompt)
1186 **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts)
1192 There are 5 (soon to be 6!) type classes:
1194 * [ArrayPrompt](#arrayprompt)
1195 - [Options](#options)
1196 - [Properties](#properties)
1197 - [Methods](#methods)
1198 - [Choices](#choices)
1199 - [Defining choices](#defining-choices)
1200 - [Choice properties](#choice-properties)
1201 - [Related prompts](#related-prompts)
1202 * [AuthPrompt](#authprompt)
1203 * [BooleanPrompt](#booleanprompt)
1204 * DatePrompt (Coming Soon!)
1205 * [NumberPrompt](#numberprompt)
1206 * [StringPrompt](#stringprompt)
1208 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.
1212 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](#select) and [Survey](#survey) prompts.
1216 In addition to the [options](#options) available to all prompts, Array prompts also support the following options.
1218 | **Option** | **Required?** | **Type** | **Description** |
1219 | ----------- | ------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------- |
1220 | `autofocus` | `no` | `string\|number` | The index or name of the choice that should have focus when the prompt loads. Only one choice may have focus at a time. | |
1221 | `stdin` | `no` | `stream` | The input stream to use for emitting keypress events. Defaults to `process.stdin`. |
1222 | `stdout` | `no` | `stream` | The output stream to use for writing the prompt to the terminal. Defaults to `process.stdout`. |
1227 Array prompts have the following instance properties and getters.
1229 | **Property name** | **Type** | **Description** |
1230 | ----------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1231 | `choices` | `array` | Array of choices that have been normalized from choices passed on the prompt options. |
1232 | `cursor` | `number` | Position of the cursor relative to the _user input (string)_. |
1233 | `enabled` | `array` | Returns an array of enabled choices. |
1234 | `focused` | `array` | Returns 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. |
1235 | `focused` | Gets the currently selected choice. Equivalent to `prompt.choices[prompt.index]`. |
1236 | `index` | `number` | Position of the pointer in the _visible list (array) of choices_. |
1237 | `limit` | `number` | The number of choices to display on-screen. |
1238 | `selected` | `array` | Either a list of enabled choices (when `options.multiple` is true) or the currently focused choice. |
1239 | `visible` | `string` | |
1243 | **Method** | **Description** |
1244 | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1245 | `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. |
1246 | `indicator()` | Returns the visual symbol that indicates whether or not a choice is checked/enabled. |
1247 | `focus()` | Sets focus on a choice, if it can be focused. |
1251 Array prompts support the `choices` option, which is the array of choices users will be able to select from when rendered in the terminal.
1253 **Type**: `string|object`
1258 const { prompt } = require('enquirer');
1260 const questions = [{
1263 message: 'Favorite color?',
1266 { name: 'red', message: 'Red', value: '#ff0000' }, //<= choice object
1267 { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object
1268 { name: 'blue', message: 'Blue', value: '#0000ff' } //<= choice object
1272 let answers = await prompt(questions);
1273 console.log('Answer:', answers.color);
1276 #### Defining choices
1278 Whether defined as a string or object, choices are normalized to the following interface:
1283 message: string | undefined;
1284 value: string | undefined;
1285 hint: string | undefined;
1286 disabled: boolean | string | undefined;
1295 message: 'Favorite fruit?',
1296 choices: ['Apple', 'Orange', 'Raspberry']
1300 Normalizes to the following when the prompt is run:
1305 message: 'Favorite fruit?',
1307 { name: 'Apple', message: 'Apple', value: 'Apple' },
1308 { name: 'Orange', message: 'Orange', value: 'Orange' },
1309 { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' }
1314 #### Choice properties
1316 The following properties are supported on `choice` objects.
1318 | **Option** | **Type** | **Description** |
1319 | ----------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1320 | `name` | `string` | The unique key to identify a choice |
1321 | `message` | `string` | The message to display in the terminal. `name` is used when this is undefined. |
1322 | `value` | `string` | Value to associate with the choice. Useful for creating key-value pairs from user choices. `name` is used when this is undefined. |
1323 | `choices` | `array` | Array of "child" choices. |
1324 | `hint` | `string` | Help message to display next to a choice. |
1325 | `role` | `string` | Determines 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] |
1326 | `enabled` | `boolean` | Enabled a choice by default. This is only supported when `options.multiple` is true or on prompts that support multiple choices, like [MultiSelect](#-multiselect). |
1327 | `disabled` | `boolean\|string` | Disable a choice so that it cannot be selected. This value may either be `true`, `false`, or a message to display. |
1328 | `indicator` | `string\|function` | Custom indicator to render for a choice (like a check or radio button). |
1330 #### Related prompts
1332 * [AutoComplete](#autocomplete-prompt)
1333 * [Form](#form-prompt)
1334 * [MultiSelect](#multiselect-prompt)
1335 * [Select](#select-prompt)
1336 * [Survey](#survey-prompt)
1342 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](#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.
1344 `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.
1348 | **Method** | **Description** |
1349 | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1350 | `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. |
1354 Auth prompt supports the `choices` option, which is the similar to the choices used in [Form Prompt](#form-prompt).
1359 const { AuthPrompt } = require('enquirer');
1361 function authenticate(value, state) {
1362 if (value.username === this.options.username && value.password === this.options.password) {
1368 const CustomAuthPrompt = AuthPrompt.create(authenticate);
1370 const prompt = new CustomAuthPrompt({
1372 message: 'Please enter your password',
1373 username: 'rajat-sr',
1374 password: '1234567',
1376 { name: 'username', message: 'username' },
1377 { name: 'password', message: 'password' }
1383 .then(answer => console.log('Authenticated?', answer))
1384 .catch(console.error);
1387 #### Related prompts
1389 * [BasicAuth Prompt](#basicauth-prompt)
1395 The `BooleanPrompt` class is used for creating prompts that display and return a boolean value.
1398 const { BooleanPrompt } = require('enquirer');
1400 const prompt = new BooleanPrompt({
1401 header: '========================',
1402 message: 'Do you love enquirer?',
1403 footer: '========================',
1407 .then(answer => console.log('Selected:', answer))
1408 .catch(console.error);
1411 **Returns**: `boolean`
1417 The `NumberPrompt` class is used for creating prompts that display and return a numerical value.
1420 const { NumberPrompt } = require('enquirer');
1422 const prompt = new NumberPrompt({
1423 header: '************************',
1424 message: 'Input the Numbers:',
1425 footer: '************************',
1429 .then(answer => console.log('Numbers are:', answer))
1430 .catch(console.error);
1433 **Returns**: `string|number` (number, or number formatted as a string)
1439 The `StringPrompt` class is used for creating prompts that display and return a string value.
1442 const { StringPrompt } = require('enquirer');
1444 const prompt = new StringPrompt({
1445 header: '************************',
1446 message: 'Input the String:',
1447 footer: '************************'
1451 .then(answer => console.log('String is:', answer))
1452 .catch(console.error);
1455 **Returns**: `string`
1461 With Enquirer 2.0, custom prompts are easier than ever to create and use.
1463 **How do I create a custom prompt?**
1465 Custom prompts are created by extending either:
1467 * Enquirer's `Prompt` class
1468 * one of the built-in [prompts](#-prompts), or
1469 * low-level [types](#-types).
1471 <!-- Example: HaiKarate Custom Prompt -->
1474 const { Prompt } = require('enquirer');
1476 class HaiKarate extends Prompt {
1477 constructor(options = {}) {
1479 this.value = options.initial || 0;
1491 this.clear(); // clear previously rendered prompt from the terminal
1492 this.write(`${this.state.message}: ${this.value}`);
1496 // Use the prompt by creating an instance of your custom prompt class.
1497 const prompt = new HaiKarate({
1498 message: 'How many sprays do you want?',
1503 .then(answer => console.log('Sprays:', answer))
1504 .catch(console.error);
1507 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`.
1510 const Enquirer = require('enquirer');
1511 const enquirer = new Enquirer();
1514 Then use the `.register()` method to add your custom prompt.
1517 enquirer.register('haikarate', HaiKarate);
1520 Now you can do the following when defining "questions".
1523 let spritzer = require('cologne-drone');
1524 let answers = await enquirer.prompt([
1528 message: 'How many sprays do you need?',
1530 async onSubmit(name, value) {
1531 await spritzer.activate(value); //<= activate drone
1544 These key combinations may be used with all prompts.
1546 | **command** | **description** |
1547 | -------------------------------- | -------------------------------------- |
1548 | <kbd>ctrl</kbd> + <kbd>c</kbd> | Cancel the prompt. |
1549 | <kbd>ctrl</kbd> + <kbd>g</kbd> | Reset the prompt to its initial state. |
1555 These combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)).
1557 | **command** | **description** |
1558 | ------------------------------ | ---------------------------------------- |
1559 | <kbd>left</kbd> | Move the cursor back one character. |
1560 | <kbd>right</kbd> | Move the cursor forward one character. |
1561 | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line |
1562 | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line |
1563 | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character |
1564 | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character |
1565 | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position |
1571 These key combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)).
1573 | **command** | **description** |
1574 | ------------------------------ | ---------------------------------------- |
1575 | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line |
1576 | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line |
1577 | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character |
1578 | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character |
1579 | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position |
1583 | **command (Mac)** | **command (Windows)** | **description** |
1584 | ----------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
1585 | <kbd>delete</kbd> | <kbd>backspace</kbd> | Delete one character to the left. |
1586 | <kbd>fn</kbd> + <kbd>delete</kbd> | <kbd>delete</kbd> | Delete one character to the right. |
1587 | <kbd>option</kbd> + <kbd>up</kbd> | <kbd>alt</kbd> + <kbd>up</kbd> | Scroll to the previous item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). |
1588 | <kbd>option</kbd> + <kbd>down</kbd> | <kbd>alt</kbd> + <kbd>down</kbd> | Scroll to the next item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). |
1592 These key combinations may be used on prompts that support _multiple_ choices, such as the [multiselect prompt](#multiselect-prompt), or the [select prompt](#select-prompt) when the `multiple` options is true.
1594 | **command** | **description** |
1595 | ----------------- | -------------------------------------------------------------------------------------------------------------------- |
1596 | <kbd>space</kbd> | Toggle the currently selected choice when `options.multiple` is true. |
1597 | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. |
1598 | <kbd>a</kbd> | Toggle all choices to be enabled or disabled. |
1599 | <kbd>i</kbd> | Invert the current selection of choices. |
1600 | <kbd>g</kbd> | Toggle the current choice group. |
1604 ### Hide/show choices
1606 | **command** | **description** |
1607 | ------------------------------- | ---------------------------------------------- |
1608 | <kbd>fn</kbd> + <kbd>up</kbd> | Decrease the number of visible choices by one. |
1609 | <kbd>fn</kbd> + <kbd>down</kbd> | Increase the number of visible choices by one. |
1613 ### Move/lock Pointer
1615 | **command** | **description** |
1616 | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
1617 | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. |
1618 | <kbd>up</kbd> | Move the pointer up. |
1619 | <kbd>down</kbd> | Move the pointer down. |
1620 | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move the pointer to the first _visible_ choice. |
1621 | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move the pointer to the last _visible_ choice. |
1622 | <kbd>shift</kbd> + <kbd>up</kbd> | Scroll up one choice without changing pointer position (locks the pointer while scrolling). |
1623 | <kbd>shift</kbd> + <kbd>down</kbd> | Scroll down one choice without changing pointer position (locks the pointer while scrolling). |
1627 | **command (Mac)** | **command (Windows)** | **description** |
1628 | -------------------------------- | --------------------- | ---------------------------------------------------------- |
1629 | <kbd>fn</kbd> + <kbd>left</kbd> | <kbd>home</kbd> | Move the pointer to the first choice in the choices array. |
1630 | <kbd>fn</kbd> + <kbd>right</kbd> | <kbd>end</kbd> | Move the pointer to the last choice in the choices array. |
1634 ## ❯ Release History
1636 Please see [CHANGELOG.md](CHANGELOG.md).
1642 MacBook Pro, Intel Core i7, 2.5 GHz, 16 GB.
1646 Time it takes for the module to load the first time (average of 3 runs):
1658 <summary><strong>Contributing</strong></summary>
1660 Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
1664 We're currently working on documentation for the following items. Please star and watch the repository for updates!
1666 * [ ] Customizing symbols
1667 * [ ] Customizing styles (palette)
1668 * [ ] Customizing rendered input
1669 * [ ] Customizing returned values
1670 * [ ] Customizing key bindings
1671 * [ ] Question validation
1672 * [ ] Choice validation
1673 * [ ] Skipping questions
1675 * [ ] Async timers: loaders, spinners and other animations
1676 * [ ] Links to examples
1680 <summary><strong>Running Tests</strong></summary>
1682 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:
1685 $ npm install && npm test
1694 <summary><strong>Building docs</strong></summary>
1696 _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
1698 To generate the readme, run the following command:
1701 $ npm install -g verbose/verb#dev verb-generate-readme && verb
1708 | **Commits** | **Contributor** |
1710 | 283 | [jonschlinkert](https://github.com/jonschlinkert) |
1711 | 82 | [doowb](https://github.com/doowb) |
1712 | 32 | [rajat-sr](https://github.com/rajat-sr) |
1713 | 20 | [318097](https://github.com/318097) |
1714 | 15 | [g-plane](https://github.com/g-plane) |
1715 | 12 | [pixelass](https://github.com/pixelass) |
1716 | 5 | [adityavyas611](https://github.com/adityavyas611) |
1717 | 5 | [satotake](https://github.com/satotake) |
1718 | 3 | [tunnckoCore](https://github.com/tunnckoCore) |
1719 | 3 | [Ovyerus](https://github.com/Ovyerus) |
1720 | 3 | [sw-yx](https://github.com/sw-yx) |
1721 | 2 | [DanielRuf](https://github.com/DanielRuf) |
1722 | 2 | [GabeL7r](https://github.com/GabeL7r) |
1723 | 1 | [AlCalzone](https://github.com/AlCalzone) |
1724 | 1 | [hipstersmoothie](https://github.com/hipstersmoothie) |
1725 | 1 | [danieldelcore](https://github.com/danieldelcore) |
1726 | 1 | [ImgBotApp](https://github.com/ImgBotApp) |
1727 | 1 | [jsonkao](https://github.com/jsonkao) |
1728 | 1 | [knpwrs](https://github.com/knpwrs) |
1729 | 1 | [yeskunall](https://github.com/yeskunall) |
1730 | 1 | [mischah](https://github.com/mischah) |
1731 | 1 | [renarsvilnis](https://github.com/renarsvilnis) |
1732 | 1 | [sbugert](https://github.com/sbugert) |
1733 | 1 | [stephencweiss](https://github.com/stephencweiss) |
1734 | 1 | [skellock](https://github.com/skellock) |
1735 | 1 | [whxaxes](https://github.com/whxaxes) |
1741 * [GitHub Profile](https://github.com/jonschlinkert)
1742 * [Twitter Profile](https://twitter.com/jonschlinkert)
1743 * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
1747 Thanks to [derhuerst](https://github.com/derhuerst), creator of prompt libraries such as [prompt-skeleton](https://github.com/derhuerst/prompt-skeleton), which influenced some of the concepts we used in our prompts.
1751 Copyright © 2018-present, [Jon Schlinkert](https://github.com/jonschlinkert).
1752 Released under the [MIT License](LICENSE).