Prompts

❯ Lightweight, beautiful and user-friendly interactive prompts

README

Prompts

❯ Prompts

version travis downloads

  <!---
install size
  --->

Lightweight, beautiful and user-friendly interactive prompts
>_ Easy to use CLI prompts to enquire users for information▌



Simple: prompts has no big dependencies nor is it broken into a dozen tiny modules that only work well together.
User friendly: prompt uses layout and colors to create beautiful cli interfaces.
Promised: uses promises and async/await. No callback hell.
Flexible: all prompts are independent and can be used on their own.
Testable: provides a way to submit answers programmatically.
Unified: consistent experience across all prompts.


split


❯ Install


  1. ```
  2. $ npm install --save prompts
  3. ```

This package supports Node 6 and above


split

❯ Usage


example prompt

  1. ```js
  2. const prompts = require('prompts');

  3. (async () => {
  4.   const response = await prompts({
  5.     type: 'number',
  6.     name: 'value',
  7.     message: 'How old are you?',
  8.     validate: value => value < 18 ? `Nightclub is 18+ only` : true
  9.   });

  10.   console.log(response); // => { value: 24 }
  11. })();
  12. ```

See [example.js](https://github.com/terkelg/prompts/blob/master/example.js) for more options.



split


❯ Examples


Single Prompt


Prompt with a single prompt object. Returns an object with the response.

  1. ```js
  2. const prompts = require('prompts');

  3. (async () => {
  4.   const response = await prompts({
  5.     type: 'text',
  6.     name: 'meaning',
  7.     message: 'What is the meaning of life?'
  8.   });

  9.   console.log(response.meaning);
  10. })();
  11. ```

Prompt Chain


Prompt with a list of prompt objects. Returns an object with the responses.
Make sure to give each prompt a unique name property to prevent overwriting values.

  1. ```js
  2. const prompts = require('prompts');

  3. const questions = [
  4.   {
  5.     type: 'text',
  6.     name: 'username',
  7.     message: 'What is your GitHub username?'
  8.   },
  9.   {
  10.     type: 'number',
  11.     name: 'age',
  12.     message: 'How old are you?'
  13.   },
  14.   {
  15.     type: 'text',
  16.     name: 'about',
  17.     message: 'Tell something about yourself',
  18.     initial: 'Why should I?'
  19.   }
  20. ];

  21. (async () => {
  22.   const response = await prompts(questions);

  23.   // => response => { username, age, about }
  24. })();
  25. ```

Dynamic Prompts


Prompt properties can be functions too.
Prompt Objects with type set to falsy values are skipped.

  1. ```js
  2. const prompts = require('prompts');

  3. const questions = [
  4.   {
  5.     type: 'text',
  6.     name: 'dish',
  7.     message: 'Do you like pizza?'
  8.   },
  9.   {
  10.     type: prev => prev == 'pizza' ? 'text' : null,
  11.     name: 'topping',
  12.     message: 'Name a topping'
  13.   }
  14. ];

  15. (async () => {
  16.   const response = await prompts(questions);
  17. })();
  18. ```


split


❯ API


prompts(prompts, options)


Type: `Function`
Returns: Object

Prompter function which takes your prompt objects and returns an object with responses.


prompts


Type: `Array|Object`

Array of prompt objects.
These are the questions the user will be prompted. You can see the list of supported prompt types here.

Prompts can be submitted (return, enter) or canceled (esc, abort, ctrl+c, ctrl+d). No property is being defined on the returned response object when a prompt is canceled.

options.onSubmit


Type: `Function`
Default: () => {}

Callback that's invoked after each prompt submission.
Its signature is (prompt, answer, answers) where prompt is the current prompt object, answer the user answer to the current question and answers the user answers so far. Async functions are supported.

Return true to quit the prompt chain and return all collected responses so far, otherwise continue to iterate prompt objects.

Example:
  1. ```js
  2. (async () => {
  3.   const questions = [{ ... }];
  4.   const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`);
  5.   const response = await prompts(questions, { onSubmit });
  6. })();
  7. ```

options.onCancel


Type: `Function`
Default: () => {}

Callback that's invoked when the user cancels/exits the prompt.
Its signature is (prompt, answers) where prompt is the current prompt object and answers the user answers so far. Async functions are supported.

Return true to continue and prevent the prompt loop from aborting.
On cancel responses collected so far are returned.

Example:
  1. ```js
  2. (async () => {
  3.   const questions = [{ ... }];
  4.   const onCancel = prompt => {
  5.     console.log('Never stop prompting!');
  6.     return true;
  7.   }
  8.   const response = await prompts(questions, { onCancel });
  9. })();
  10. ```

override


Type: Function

Preanswer questions by passing an object with answers to prompts.override.
Powerful when combined with arguments of process.

Example
  1. ```js
  2. const prompts = require('prompts');
  3. prompts.override(require('yargs').argv);

  4. (async () => {
  5.   const response = await prompts([
  6.     {
  7.       type: 'text',
  8.       name: 'twitter',
  9.       message: `What's your twitter handle?`
  10.     },
  11.     {
  12.       type: 'multiselect',
  13.       name: 'color',
  14.       message: 'Pick colors',
  15.       choices: [
  16.         { title: 'Red', value: '#ff0000' },
  17.         { title: 'Green', value: '#00ff00' },
  18.         { title: 'Blue', value: '#0000ff' }
  19.       ],
  20.     }
  21.   ]);

  22.   console.log(response);
  23. })();
  24. ```

inject(values)


Type: `Function`

Programmatically inject responses. This enables you to prepare the responses ahead of time.
If any injected value is found the prompt is immediately resolved with the injected value.
This feature is intended for testing only.

values


Type: Array

Array with values to inject. Resolved values are removed from the internal inject array.
Each value can be an array of values in order to provide answers for a question asked multiple times.
If a value is an instance of Error it will simulate the user cancelling/exiting the prompt.

Example:
  1. ```js
  2. const prompts = require('prompts');

  3. prompts.inject([ '@terkelg', ['#ff0000', '#0000ff'] ]);

  4. (async () => {
  5.   const response = await prompts([
  6.     {
  7.       type: 'text',
  8.       name: 'twitter',
  9.       message: `What's your twitter handle?`
  10.     },
  11.     {
  12.       type: 'multiselect',
  13.       name: 'color',
  14.       message: 'Pick colors',
  15.       choices: [
  16.         { title: 'Red', value: '#ff0000' },
  17.         { title: 'Green', value: '#00ff00' },
  18.         { title: 'Blue', value: '#0000ff' }
  19.       ],
  20.     }
  21.   ]);

  22.   // => { twitter: 'terkelg', color: [ '#ff0000', '#0000ff' ] }
  23. })();
  24. ```

split


❯ Prompt Objects


Prompts Objects are JavaScript objects that define the "questions" and the type of prompt.
Almost all prompt objects have the following properties:

  1. ```js
  2. {
  3.   type: String | Function,
  4.   name: String | Function,
  5.   message: String | Function,
  6.   initial: String | Function | Async Function
  7.   format: Function | Async Function,
  8.   onRender: Function
  9.   onState: Function
  10.   stdin: Readable
  11.   stdout: Writeable
  12. }
  13. ```

Each property be of type function and will be invoked right before prompting the user.

The function signature is (prev, values, prompt), where prev is the value from the previous prompt,
values is the response object with all values collected so far and prompt is the previous prompt object.

Function example:
  1. ```js
  2. {
  3.   type: prev => prev > 3 ? 'confirm' : null,
  4.   name: 'confirm',
  5.   message: (prev, values) => `Please confirm that you eat ${values.dish} times ${prev} a day?`
  6. }
  7. ```

The above prompt will be skipped if the value of the previous prompt is less than 3.

type


Type: String|Function

Defines the type of prompt to display. See the list of prompt types for valid values.

If type is a falsy value the prompter will skip that question.
  1. ```js
  2. {
  3.   type: null,
  4.   name: 'forgetme',
  5.   message: `I'll never be shown anyway`,
  6. }
  7. ```

name


Type: String|Function

The response will be saved under this key/property in the returned response object.
In case you have multiple prompts with the same name only the latest response will be stored.

Make sure to give prompts unique names if you don't want to overwrite previous values.


message


Type: String|Function

The message to be displayed to the user.

initial


Type: String|Function

Optional default prompt value. Async functions are supported too.

format


Type: Function

Receive the user input and return the formatted value to be used inside the program.
The value returned will be added to the response object.

The function signature is (val, values), where val is the value from the current prompt and
values is the current response object in case you need to format based on previous responses.

Example:
  1. ```js
  2. {
  3.   type: 'number',
  4.   name: 'price',
  5.   message: 'Enter price',
  6.   format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val);
  7. }
  8. ```

onRender


Type: Function

Callback for when the prompt is rendered.
The function receives kleur as its first argument andthis refers to the current prompt.

Example:
  1. ```js
  2. {
  3.   type: 'number',
  4.   message: 'This message will be overridden',
  5.   onRender(kleur) {
  6.     this.msg = kleur.cyan('Enter a number');
  7.   }
  8. }
  9. ```

onState


Type: Function

Callback for when the state of the current prompt changes.
The function signature is (state) where state is an object with a snapshot of the current state.
The state object has two properties value and aborted. E.g { value: 'This is ', aborted: false }

stdin and stdout


Type: Stream

By default, prompts uses process.stdin for receiving input and process.stdout for writing output.
If you need to use different streams, for instance process.stderr, you can set these with the stdin and stdout properties.


split


❯ Types




text(message, [initial], [style])

Text prompt for free text input.


Hit tab to autocomplete to `initial` value when provided.

Example

text prompt

  1. ```js
  2. {
  3.   type: 'text',
  4.   name: 'value',
  5.   message: `What's your twitter handle?`
  6. }
  7. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`string`Default
style`string`Render
format`function`Receive
validate`function`Receive
onRender`function`On
onState`function`On

↑ back to: Prompt types


password(message, [initial])

Password prompt with masked input.


This prompt is a similar to a prompt of type 'text' with style set to 'password'.

Example

password prompt

  1. ```js
  2. {
  3.   type: 'password',
  4.   name: 'value',
  5.   message: 'Tell me a secret'
  6. }
  7. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`string`Default
format`function`Receive
validate`function`Receive
onRender`function`On
onState`function`On

↑ back to: Prompt types


invisible(message, [initial])

Prompts user for invisible text input.


This prompt is working like sudo where the input is invisible.
This prompt is a similar to a prompt of type 'text' with style set to 'invisible'.

Example

invisible prompt

  1. ```js
  2. {
  3.   type: 'invisible',
  4.   name: 'value',
  5.   message: 'Enter password'
  6. }
  7. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`string`Default
format`function`Receive
validate`function`Receive
onRender`function`On
onState`function`On

↑ back to: Prompt types


number(message, initial, [max], [min], [style])

Prompts user for number input.


You can type in numbers and use up/down to increase/decrease the value. Only numbers are allowed as input. Hit tab to autocomplete to `initial` value when provided.

Example

number prompt

  1. ```js
  2. {
  3.   type: 'number',
  4.   name: 'value',
  5.   message: 'How old are you?',
  6.   initial: 0,
  7.   style: 'default',
  8.   min: 2,
  9.   max: 10
  10. }
  11. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`number`Default
format`function`Receive
validate`function`Receive
max`number`Max
min`number`Min
float`boolean`Allow
round`number`Round
increment`number`Increment
style`string`Render
onRender`function`On
onState`function`On

↑ back to: Prompt types


confirm(message, [initial])

Classic yes/no prompt.


Hit y or n to confirm/reject.

Example

confirm prompt

  1. ```js
  2. {
  3.   type: 'confirm',
  4.   name: 'value',
  5.   message: 'Can you confirm?',
  6.   initial: true
  7. }
  8. ```


Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`boolean`Default
format`function`Receive
onRender`function`On
onState`function`On

↑ back to: Prompt types


list(message, [initial])

List prompt that return an array.


Similar to the text prompt, but the output is an Array containing the
string separated by separator.

  1. ```js
  2. {
  3.   type: 'list',
  4.   name: 'value',
  5.   message: 'Enter keywords',
  6.   initial: '',
  7.   separator: ','
  8. }
  9. ```

list prompt


ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`boolean`Default
format`function`Receive
separator`string`String
onRender`function`On
onState`function`On

↑ back to: Prompt types


toggle(message, [initial], [active], [inactive])

Interactive toggle/switch prompt.


Use tab or arrow keys/tab/space to switch between options.

Example

toggle prompt

  1. ```js
  2. {
  3.   type: 'toggle',
  4.   name: 'value',
  5.   message: 'Can you confirm?',
  6.   initial: true,
  7.   active: 'yes',
  8.   inactive: 'no'
  9. }
  10. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`boolean`Default
format`function`Receive
active`string`Text
inactive`string`Text
onRender`function`On
onState`function`On

↑ back to: Prompt types


select(message, choices, [initial], [hint], [warn])

Interactive select prompt.


Use up/down to navigate. Use tab to cycle the list.

Example

select prompt

  1. ```js
  2. {
  3.   type: 'select',
  4.   name: 'value',
  5.   message: 'Pick a color',
  6.   choices: [
  7.     { title: 'Red', description: 'This option has a description', value: '#ff0000' },
  8.     { title: 'Green', value: '#00ff00', disabled: true },
  9.     { title: 'Blue', value: '#0000ff' }
  10.   ],
  11.   initial: 1
  12. }
  13. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`number`Index
format`function`Receive
hint`string`Hint
warn`string`Message
choices`Array`Array
onRender`function`On
onState`function`On

↑ back to: Prompt types


multiselect(message, choices, [initial], [max], [hint], [warn])

autocompleteMultiselect(same)

Interactive multi-select prompt.

Autocomplete is a searchable multiselect prompt with the same options. Useful for long lists.


Use space to toggle select/unselect and up/down to navigate. Use tab to cycle the list. You can also use right to select and left to deselect.
By default this prompt returns an array containing the values of the selected items - not their display title.

Example

multiselect prompt

  1. ```js
  2. {
  3.   type: 'multiselect',
  4.   name: 'value',
  5.   message: 'Pick colors',
  6.   choices: [
  7.     { title: 'Red', value: '#ff0000' },
  8.     { title: 'Green', value: '#00ff00', disabled: true },
  9.     { title: 'Blue', value: '#0000ff', selected: true }
  10.   ],
  11.   max: 2,
  12.   hint: '- Space to select. Return to submit'
  13. }
  14. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
format`function`Receive
instructions`string`Prompt
choices`Array`Array
optionsPerPage`number`Number
min`number`Min
max`number`Max
hint`string`Hint
warn`string`Message
onRender`function`On
onState`function`On

This is one of the few prompts that don't take a initial value.
If you want to predefine selected values, give the choice object an selected property of true.

↑ back to: Prompt types


autocomplete(message, choices, [initial], [suggest], [limit], [style])

Interactive auto complete prompt.


The prompt will list options based on user input. Type to filter the list.
Use / to navigate. Use tab to cycle the result. Use Page Up/Page Down (on Mac: fn + / ) to change page. Hit enter to select the highlighted item below the prompt.

The default suggests function is sorting based on the title property of the choices.
You can overwrite how choices are being filtered by passing your own suggest function.

Example

auto complete prompt

  1. ```js
  2. {
  3.   type: 'autocomplete',
  4.   name: 'value',
  5.   message: 'Pick your favorite actor',
  6.   choices: [
  7.     { title: 'Cage' },
  8.     { title: 'Clooney', value: 'silver-fox' },
  9.     { title: 'Gyllenhaal' },
  10.     { title: 'Gibson' },
  11.     { title: 'Grant' }
  12.   ]
  13. }
  14. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
format`function`Receive
choices`Array`Array
suggest`function`Filter
limit`number`Max
style`string`Render
initial`stringnumber`
clearFirst`boolean`The
fallback`string`Fallback
onRender`function`On
onState`function`On

Example on what a suggest function might look like:
  1. ```js
  2. const suggestByTitle = (input, choices) =>
  3.     Promise.resolve(choices.filter(i => i.title.slice(0, input.length) === input))
  4. ```

↑ back to: Prompt types


date(message, [initial], [warn])

Interactive date prompt.


Use left/right/tab to navigate. Use up/down to change date.

Example

date prompt

  1. ```js
  2. {
  3.   type: 'date',
  4.   name: 'value',
  5.   message: 'Pick a date',
  6.   initial: new Date(1997, 09, 12),
  7.   validate: date => date > Date.now() ? 'Not in the future' : true
  8. }
  9. ```

Options

ParamTypeDescription
-----:--:-----------
message`string`Prompt
initial`date`Default
locales`object`Use
mask`string`The
validate`function`Receive
onRender`function`On
onState`function`On

Default locales:

  1. ```javascript
  2. {
  3.   months: [
  4.     'January', 'February', 'March', 'April',
  5.     'May', 'June', 'July', 'August',
  6.     'September', 'October', 'November', 'December'
  7.   ],
  8.   monthsShort: [
  9.     'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  10.     'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  11.   ],
  12.   weekdays: [
  13.     'Sunday', 'Monday', 'Tuesday', 'Wednesday',
  14.     'Thursday', 'Friday', 'Saturday'
  15.   ],
  16.   weekdaysShort: [
  17.     'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
  18.   ]
  19. }
  20. ```
>Formatting: See full list of formatting options in the wiki

split

↑ back to: Prompt types


❯ Credit

Many of the prompts are based on the work of derhuerst.


❯ License