Stylish, intuitive and user-friendly prompts, for Node.js. Used by eslint, webpack, yarn, pm2, pnpm, RedwoodJS, FactorJS, salesforce, Cypress, Google Lighthouse, Generate, tencent cloudbase, lint-staged, gluegun, hygen, hardhat, AWS Amplify, GitHub Actions Toolkit, @airbnb/nimbus, and many others! Please follow Enquirer's author: https://github.com/jonschlinkert
Installations
npm install enquirer
Releases
Unable to fetch releases
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
>=8.6
Typescript Support
Yes
Node Version
18.16.1
NPM Version
9.5.1
Statistics
7,704 Stars
564 Commits
285 Forks
45 Watching
3 Branches
49 Contributors
Updated on 26 Nov 2024
Bundle Size
74.01 kB
Minified
22.13 kB
Minified + Gzipped
Languages
JavaScript (83.63%)
SCSS (13.11%)
Handlebars (1.79%)
TypeScript (1.2%)
CSS (0.27%)
Total Downloads
Cumulative downloads
Total Downloads
2,968,157,123
Last day
-11.1%
3,318,321
Compared to previous day
Last week
1.6%
19,952,756
Compared to previous week
Last month
15.4%
81,144,764
Compared to previous month
Last year
9.8%
844,204,920
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Enquirer
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)
The terminal in all examples is Hyper, theme is hyper-monokai-extended.
See more prompt examples
Created by jonschlinkert and 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.
- 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!
>_ Ready to start making prompts your users will love? ▌
❯ 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:
1npm install enquirer --save
Install with yarn:
1yarn add enquirer
(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 the prompt
method.
1const { prompt } = require('enquirer'); 2 3const response = await prompt({ 4 type: 'input', 5 name: 'username', 6 message: 'What is your username?' 7}); 8 9console.log(response); // { username: 'jonschlinkert' }
(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.
1const response = await prompt([ 2 { 3 type: 'input', 4 name: 'name', 5 message: 'What is your name?' 6 }, 7 { 8 type: 'input', 9 name: 'username', 10 message: 'What is your username?' 11 } 12]); 13 14console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' }
Different ways to run enquirer
1. By importing the specific built-in prompt
1const { Confirm } = require('enquirer'); 2 3const prompt = new Confirm({ 4 name: 'question', 5 message: 'Did you like enquirer?' 6}); 7 8prompt.run() 9 .then(answer => console.log('Answer:', answer));
2. By passing the options to prompt
1const { prompt } = require('enquirer'); 2 3prompt({ 4 type: 'confirm', 5 name: 'question', 6 message: 'Did you like enquirer?' 7}) 8 .then(answer => console.log('Answer:', answer));
Jump to: Getting Started · Prompts · Options · Key Bindings
❯ Enquirer
Enquirer is a prompt runner
Add Enquirer to your JavaScript project with following line of code.
1const Enquirer = require('enquirer');
The main export of this library is the Enquirer
class, which has methods and features designed to simplify running prompts.
1const { prompt } = require('enquirer'); 2const questions = [ 3 { 4 type: 'input', 5 name: 'username', 6 message: 'What is your username?' 7 }, 8 { 9 type: 'password', 10 name: 'password', 11 message: 'What is your password?' 12 } 13]; 14 15const answers = await prompt(questions); 16console.log(answers);
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 using enquirer.prompt()
.
Use this approach if you need to modify a prompt instance, or listen for events on the prompt.
Example
1const { Input } = require('enquirer'); 2const prompt = new Input({ 3 name: 'username', 4 message: 'What is your username?' 5}); 6 7prompt.run() 8 .then(answer => console.log('Username:', answer)) 9 .catch(console.error);
Enquirer
Create an instance of Enquirer
.
Params
options
{Object}: (optional) Options to use with all prompts.answers
{Object}: (optional) Answers object to initialize with.
Example
1const Enquirer = require('enquirer'); 2const enquirer = new Enquirer();
register()
Register a custom prompt type.
Params
type
{String}fn
{Function|Prompt}:Prompt
class, or a function that returns aPrompt
class.returns
{Object}: Returns the Enquirer instance
Example
1const Enquirer = require('enquirer'); 2const enquirer = new Enquirer(); 3enquirer.register('customType', require('./custom-prompt'));
prompt()
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
1const Enquirer = require('enquirer'); 2const enquirer = new Enquirer(); 3 4const response = await enquirer.prompt({ 5 type: 'input', 6 name: 'username', 7 message: 'What is your username?' 8}); 9console.log(response);
use()
Use an enquirer plugin.
Params
plugin
{Function}: Plugin function that takes an instance of Enquirer.returns
{Object}: Returns the Enquirer instance.
Example
1const Enquirer = require('enquirer'); 2const enquirer = new Enquirer(); 3const plugin = enquirer => { 4 // do stuff to enquire instance 5}; 6enquirer.use(plugin);
Enquirer#prompt
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
1const { prompt } = require('enquirer'); 2const response = await prompt({ 3 type: 'input', 4 name: 'username', 5 message: 'What is your username?' 6}); 7console.log(response);
❯ 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 used by other prompts - Built-in prompts
- Prompt Types - The base
Prompt
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.
1const { Prompt } = require('enquirer'); 2class 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:
1{ 2 // required 3 type: string | function, 4 name: string | function, 5 message: string | function | async function, 6 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}
Each property of the options object is described below:
Property | Required? | Type | Description |
---|---|---|---|
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. |
name | yes | string|function | Used as the key for the answer on the returned values (answers) object. |
message | yes | string|function | The message to display when the prompt is rendered in the terminal. |
skip | no | boolean|function | If true it will not ask that prompt. |
initial | no | string|function | The default value to return if the user does not supply a value. |
format | no | function | Function to format user input in the terminal. |
result | no | function | Function to format the final submitted value before it's returned. |
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. |
Example usage
1const { prompt } = require('enquirer'); 2 3const question = { 4 type: 'input', 5 name: 'username', 6 message: 'What is your username?' 7}; 8 9prompt(question) 10 .then(answer => console.log('Answer:', answer)) 11 .catch(console.error);
Built-in prompts
- AutoComplete Prompt
- BasicAuth Prompt
- Confirm Prompt
- Form Prompt
- Input Prompt
- Invisible Prompt
- List Prompt
- MultiSelect Prompt
- Numeral Prompt
- Password Prompt
- Quiz Prompt
- Survey Prompt
- Scale Prompt
- Select Prompt
- Sort Prompt
- Snippet Prompt
- Toggle Prompt
AutoComplete Prompt
Prompt that auto-completes as the user types, and returns the selected value as a string.
Example Usage
1const { AutoComplete } = require('enquirer'); 2 3const 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 32prompt.run() 33 .then(answer => console.log('Answer:', answer)) 34 .catch(console.error);
AutoComplete Options
Option | Type | Default | Description |
---|---|---|---|
highlight | function | dim version of primary style | The color to use when "highlighting" characters in the list that match user input. |
multiple | boolean | false | Allow multiple choices to be selected. |
suggest | function | Greedy 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. |
initial | number | 0 | Preselected item in the list of choices. |
footer | function | None | Function 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.
Example Usage
1const { BasicAuth } = require('enquirer'); 2 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 11 prompt 12 .run() 13 .then(answer => console.log('Answer:', answer)) 14 .catch(console.error);
↑ back to: Getting Started · Prompts
Confirm Prompt
Prompt that returns true
or false
.
Example Usage
1const { Confirm } = require('enquirer'); 2 3const prompt = new Confirm({ 4 name: 'question', 5 message: 'Want to answer?' 6}); 7 8prompt.run() 9 .then(answer => console.log('Answer:', answer)) 10 .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.
Example Usage
1const { Form } = require('enquirer'); 2 3const 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 13prompt.run() 14 .then(value => console.log('Answer:', value)) 15 .catch(console.error);
Related prompts
↑ back to: Getting Started · Prompts
Input Prompt
Prompt that takes user input and returns a string.
Example Usage
1const { Input } = require('enquirer'); 2const prompt = new Input({ 3 message: 'What is your username?', 4 initial: 'jonschlinkert' 5}); 6 7prompt.run() 8 .then(answer => console.log('Answer:', answer)) 9 .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.
Example Usage
1const { Invisible } = require('enquirer'); 2const prompt = new Invisible({ 3 name: 'secret', 4 message: 'What is your secret?' 5}); 6 7prompt.run() 8 .then(answer => console.log('Answer:', { secret: answer })) 9 .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.
Example Usage
1const { List } = require('enquirer'); 2const prompt = new List({ 3 name: 'keywords', 4 message: 'Type comma-separated keywords' 5}); 6 7prompt.run() 8 .then(answer => console.log('Answer:', answer)) 9 .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.
Example Usage
1const { MultiSelect } = require('enquirer'); 2 3const 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 27prompt.run() 28 .then(answer => console.log('Answer:', answer)) 29 .catch(console.error); 30 31// 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
1const { MultiSelect } = require('enquirer'); 2 3const 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 30prompt.run() 31 .then(answer => console.log('Answer:', answer)) 32 .catch(console.error); 33 34// Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' }
Example alternate labels
1const { MultiSelect } = require('enquirer'); 2 3const prompt = new MultiSelect({ 4 name: 'color', 5 message: 'Pick a flavor', 6 choices: [ 7 { message: 'Negative Red', name: 'cyan', value: '#00ffff' }, 8 { message: 'Lights Out', name: 'black', value: '#000000' }, 9 { message: 'The Ocean', name: 'blue', value: '#0000ff' }, 10 ] 11}); 12 13prompt.run() 14 .then(answer => console.log('Answer:', answer)) 15 .catch(console.error);
Related prompts
↑ back to: Getting Started · Prompts
Numeral Prompt
Prompt that takes a number as input.
Example Usage
1const { NumberPrompt } = require('enquirer'); 2 3const prompt = new NumberPrompt({ 4 name: 'number', 5 message: 'Please enter a number' 6}); 7 8prompt.run() 9 .then(answer => console.log('Answer:', answer)) 10 .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
Example Usage
1const { Password } = require('enquirer'); 2 3const prompt = new Password({ 4 name: 'password', 5 message: 'What is your password?' 6}); 7 8prompt.run() 9 .then(answer => console.log('Answer:', answer)) 10 .catch(console.error);
Related prompts
↑ back to: Getting Started · Prompts
Quiz Prompt
Prompt that allows the user to play multiple-choice quiz questions.
Example Usage
1const { Quiz } = require('enquirer'); 2 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 10 prompt 11 .run() 12 .then(answer => { 13 if (answer.correct) { 14 console.log('Correct!'); 15 } else { 16 console.log(`Wrong! Correct answer is ${answer.correctAnswer}`); 17 } 18 }) 19 .catch(console.error);
Quiz Options
Option | Type | Required | Description |
---|---|---|---|
choices | array | Yes | The list of possible answers to the quiz question. |
correctChoice | number | Yes | Index 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.
Example Usage
1const { Survey } = require('enquirer');
2
3const 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
38prompt.run()
39 .then(value => console.log('ANSWERS:', value))
40 .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.
Example Usage
1const { Scale } = require('enquirer');
2const prompt = new Scale({
3 name: 'experience',
4 message: 'Please rate your experience',
5 scale: [
6 { name: '1', message: 'Strongly Disagree' },
7 { name: '2', message: 'Disagree' },
8 { name: '3', message: 'Neutral' },
9 { name: '4', message: 'Agree' },
10 { name: '5', message: 'Strongly Agree' }
11 ],
12 margin: [0, 0, 2, 1],
13 choices: [
14 {
15 name: 'interface',
16 message: 'The website has a friendly interface.',
17 initial: 2
18 },
19 {
20 name: 'navigation',
21 message: 'The website is easy to navigate.',
22 initial: 2
23 },
24 {
25 name: 'images',
26 message: 'The website usually has good images.',
27 initial: 2
28 },
29 {
30 name: 'upload',
31 message: 'The website makes it easy to upload images.',
32 initial: 2
33 },
34 {
35 name: 'colors',
36 message: 'The website has a pleasing color palette.',
37 initial: 2
38 }
39 ]
40});
41
42prompt.run()
43 .then(value => console.log('ANSWERS:', value))
44 .catch(console.error);
Related prompts
↑ back to: Getting Started · Prompts
Select Prompt
Prompt that allows the user to select from a list of options.
Example Usage
1const { Select } = require('enquirer'); 2 3const prompt = new Select({ 4 name: 'color', 5 message: 'Pick a flavor', 6 choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange'] 7}); 8 9prompt.run() 10 .then(answer => console.log('Answer:', answer)) 11 .catch(console.error);
Example key-value pairs
1const { Select } = require('enquirer'); 2 3const prompt = new Select({ 4 name: 'color', 5 message: 'Pick a color', 6 choices: [ 7 { name: 'cyan', value: '#00ffff' }, 8 { name: 'black', value: '#000000' }, 9 { name: 'blue', value: '#0000ff' }, 10 ] 11}); 12 13prompt.run() 14 .then(answer => console.log('Answer:', answer)) 15 .catch(console.error);
Example alternate labels
1const { Select } = require('enquirer'); 2 3const prompt = new Select({ 4 name: 'color', 5 message: 'Pick a color', 6 choices: [ 7 { message: 'Negative Red', name: 'cyan', value: '#00ffff' }, 8 { message: 'Lights Out', name: 'black', value: '#000000' }, 9 { message: 'The Ocean', name: 'blue', value: '#0000ff' }, 10 ] 11}); 12 13prompt.run() 14 .then(answer => console.log('Answer:', answer)) 15 .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.
Example Usage
1const colors = require('ansi-colors'); 2const { Sort } = require('enquirer'); 3const prompt = new Sort({ 4 name: 'colors', 5 message: 'Sort the colors in order of preference', 6 hint: 'Top is best, bottom is worst', 7 numbered: true, 8 choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({ 9 name: n, 10 message: colors[n](n) 11 })) 12}); 13 14prompt.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);
Related prompts
↑ back to: Getting Started · Prompts
Snippet Prompt
Prompt that allows the user to replace placeholders in a snippet of code or text.
Example Usage
1const semver = require('semver'); 2const { Snippet } = require('enquirer'); 3const prompt = new Snippet({ 4 name: 'username', 5 message: 'Fill out the fields in package.json', 6 required: true, 7 fields: [ 8 { 9 name: 'author_name', 10 message: 'Author Name' 11 }, 12 { 13 name: 'version', 14 validate(value, state, item, index) { 15 if (item && item.name === 'version' && !semver.valid(value)) { 16 return prompt.styles.danger('version should be a valid semver value'); 17 } 18 return true; 19 } 20 } 21 ], 22 template: `{ 23 "name": "\${name}", 24 "description": "\${description}", 25 "version": "\${version}", 26 "homepage": "https://github.com/\${username}/\${name}", 27 "author": "\${author_name} (https://github.com/\${username})", 28 "repository": "\${username}/\${name}", 29 "license": "\${license:ISC}" 30} 31` 32}); 33 34prompt.run() 35 .then(answer => console.log('Answer:', answer.result)) 36 .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
.
Example Usage
1const { Toggle } = require('enquirer'); 2 3const prompt = new Toggle({ 4 message: 'Want to answer?', 5 enabled: 'Yep', 6 disabled: 'Nope' 7}); 8 9prompt.run() 10 .then(answer => console.log('Answer:', answer)) 11 .catch(console.error);
Related prompts
↑ back to: Getting Started · Prompts
Prompt Types
There are 5 (soon to be 6!) type classes:
- ArrayPrompt
- AuthPrompt
- BooleanPrompt
- DatePrompt (Coming Soon!)
- NumberPrompt
- StringPrompt
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 index or name of the choice that should have focus when the prompt loads. Only one choice may have focus at a time. |
stdin | no | stream | The input stream to use for emitting keypress events. Defaults to process.stdin . |
stdout | no | stream | The 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 name | Type | Description |
---|---|---|
choices | array | Array of choices that have been normalized from choices passed on the prompt options. |
cursor | number | Position of the cursor relative to the user input (string). |
enabled | array | Returns an array of enabled choices. |
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. |
focused | Gets the currently selected choice. Equivalent to prompt.choices[prompt.index] . | |
index | number | Position of the pointer in the visible list (array) of choices. |
limit | number | The number of choices to display on-screen. |
selected | array | Either a list of enabled choices (when options.multiple is true) or the currently focused choice. |
visible | string |
Methods
Method | Description |
---|---|
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
1const { prompt } = require('enquirer'); 2 3const 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 15let answers = await prompt(questions); 16console.log('Answer:', answers.color);
Defining choices
Whether defined as a string or object, choices are normalized to the following interface:
1{ 2 name: string; 3 message: string | undefined; 4 value: string | undefined; 5 hint: string | undefined; 6 disabled: boolean | string | undefined; 7}
Example
1const question = { 2 name: 'fruit', 3 message: 'Favorite fruit?', 4 choices: ['Apple', 'Orange', 'Raspberry'] 5};
Normalizes to the following when the prompt is run:
1const question = { 2 name: 'fruit', 3 message: 'Favorite fruit?', 4 choices: [ 5 { name: 'Apple', message: 'Apple', value: 'Apple' }, 6 { name: 'Orange', message: 'Orange', value: 'Orange' }, 7 { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' } 8 ] 9};
Choice properties
The following properties are supported on choice
objects.
Option | Type | Description |
---|---|---|
name | string | The unique key to identify a choice |
message | string | The message to display in the terminal. name is used when this is undefined. |
value | string | Value to associate with the choice. Useful for creating key-value pairs from user choices. name is used when this is undefined. |
choices | array | Array of "child" choices. |
hint | string | Help message to display next to a choice. |
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] |
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. |
disabled | boolean|string | Disable a choice so that it cannot be selected. This value may either be true , false , or a message to display. |
indicator | string|function | Custom indicator to render for a choice (like a check or radio button). |
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 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
Method | Description |
---|---|
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
1const { AuthPrompt } = require('enquirer'); 2 3function authenticate(value, state) { 4 if (value.username === this.options.username && value.password === this.options.password) { 5 return true; 6 } 7 return false; 8} 9 10const CustomAuthPrompt = AuthPrompt.create(authenticate); 11 12const prompt = new CustomAuthPrompt({ 13 name: 'password', 14 message: 'Please enter your password', 15 username: 'rajat-sr', 16 password: '1234567', 17 choices: [ 18 { name: 'username', message: 'username' }, 19 { name: 'password', message: 'password' } 20 ] 21}); 22 23prompt 24 .run() 25 .then(answer => console.log('Authenticated?', answer)) 26 .catch(console.error);
Related prompts
BooleanPrompt
The BooleanPrompt
class is used for creating prompts that display and return a boolean value.
1const { BooleanPrompt } = require('enquirer'); 2 3const prompt = new BooleanPrompt({ 4 header: '========================', 5 message: 'Do you love enquirer?', 6 footer: '========================', 7}); 8 9prompt.run() 10 .then(answer => console.log('Selected:', answer)) 11 .catch(console.error);
Returns: boolean
NumberPrompt
The NumberPrompt
class is used for creating prompts that display and return a numerical value.
1const { NumberPrompt } = require('enquirer'); 2 3const prompt = new NumberPrompt({ 4 header: '************************', 5 message: 'Input the Numbers:', 6 footer: '************************', 7}); 8 9prompt.run() 10 .then(answer => console.log('Numbers are:', answer)) 11 .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.
1const { StringPrompt } = require('enquirer'); 2 3const prompt = new StringPrompt({ 4 header: '************************', 5 message: 'Input the String:', 6 footer: '************************' 7}); 8 9prompt.run() 10 .then(answer => console.log('String is:', answer)) 11 .catch(console.error);
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:
1const { Prompt } = require('enquirer'); 2 3class 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 23// Use the prompt by creating an instance of your custom prompt class. 24const prompt = new HaiKarate({ 25 message: 'How many sprays do you want?', 26 initial: 10 27}); 28 29prompt.run() 30 .then(answer => console.log('Sprays:', answer)) 31 .catch(console.error);
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
.
1const Enquirer = require('enquirer'); 2const enquirer = new Enquirer();
Then use the .register()
method to add your custom prompt.
1enquirer.register('haikarate', HaiKarate);
Now you can do the following when defining "questions".
1let spritzer = require('cologne-drone'); 2let answers = await enquirer.prompt([ 3 { 4 type: 'haikarate', 5 name: 'cologne', 6 message: 'How many sprays do you need?', 7 initial: 10, 8 async onSubmit(name, value) { 9 await spritzer.activate(value); //<= activate drone 10 return value; 11 } 12 } 13]);
❯ Key Bindings
All prompts
These key combinations may be used with all prompts.
command | description |
---|---|
ctrl + c | Cancel the prompt. |
ctrl + g | Reset the prompt to its initial state. |
Move cursor
These combinations may be used on prompts that support user input (eg. input prompt, password prompt, and invisible prompt).
command | description |
---|---|
left | Move the cursor back one character. |
right | Move the cursor forward one character. |
ctrl + a | Move cursor to the start of the line |
ctrl + e | Move cursor to the end of the line |
ctrl + b | Move cursor back one character |
ctrl + f | Move cursor forward one character |
ctrl + x | Toggle between first and cursor position |
Edit Input
These key combinations may be used on prompts that support user input (eg. input prompt, password prompt, and invisible prompt).
command | description |
---|---|
ctrl + a | Move cursor to the start of the line |
ctrl + e | Move cursor to the end of the line |
ctrl + b | Move cursor back one character |
ctrl + f | Move cursor forward one character |
ctrl + x | Toggle between first and cursor position |
command (Mac) | command (Windows) | description |
---|---|---|
delete | backspace | Delete one character to the left. |
fn + delete | delete | Delete one character to the right. |
option + up | alt + up | Scroll to the previous item in history (Input prompt only, when history is enabled). |
option + down | alt + down | Scroll to the next item in history (Input prompt only, when history is enabled). |
Select choices
These key combinations may be used on prompts that support multiple choices, such as the multiselect prompt, or the select prompt when the multiple
options is true.
command | description |
---|---|
space | Toggle the currently selected choice when options.multiple is true. |
number | Move the pointer to the choice at the given index. Also toggles the selected choice when options.multiple is true. |
a | Toggle all choices to be enabled or disabled. |
i | Invert the current selection of choices. |
g | Toggle the current choice group. |
Hide/show choices
command | description |
---|---|
fn + up | Decrease the number of visible choices by one. |
fn + down | Increase the number of visible choices by one. |
Move/lock Pointer
command | description |
---|---|
number | Move the pointer to the choice at the given index. Also toggles the selected choice when options.multiple is true. |
up | Move the pointer up. |
down | Move the pointer down. |
ctrl + a | Move the pointer to the first visible choice. |
ctrl + e | Move the pointer to the last visible choice. |
shift + up | Scroll up one choice without changing pointer position (locks the pointer while scrolling). |
shift + down | Scroll down one choice without changing pointer position (locks the pointer while scrolling). |
command (Mac) | command (Windows) | description |
---|---|---|
fn + left | home | Move the pointer to the first choice in the choices array. |
fn + right | end | Move the pointer to the last choice in the choices array. |
❯ 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):
enquirer: 4.013ms
inquirer: 286.717ms
❯ 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:
1npm install && npm test
1yarn && yarn test
Building docs
(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)
To generate the readme, run the following command:
1npm install -g verbose/verb#dev verb-generate-readme && verb
Contributors
Author
Jon Schlinkert
Credit
Thanks to derhuerst, creator of prompt libraries such as prompt-skeleton, which influenced some of the concepts we used in our prompts.
License
Copyright © 2018-present, Jon Schlinkert. Released under the MIT License.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 15/29 approved changesets -- score normalized to 5
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 16 are checked with a SAST tool
Score
3.7
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More