Convert Figma logo to code with AI

terkelg logoprompts

❯ Lightweight, beautiful and user-friendly interactive prompts

8,821
304
8,821
148

Top Related Projects

A collection of common interactive command line user interfaces.

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

node.js command-line interfaces made easy

3,530

🐈 CLI app helper

11,041

yargs the modern, pirate-themed successor to optimist.

8,977

CLI for generating, building, and releasing oclif CLIs. Built by Salesforce.

Quick Overview

Prompts is a lightweight, beautiful, and user-friendly command-line interface for Node.js. It provides an easy way to create interactive command-line prompts with a wide variety of input types, making it ideal for building CLI applications or gathering user input in Node.js scripts.

Pros

  • Simple and intuitive API for creating various types of prompts
  • Highly customizable with support for custom styles and themes
  • Lightweight with minimal dependencies
  • Supports both CommonJS and ES modules

Cons

  • Limited to Node.js environments, not suitable for browser-based applications
  • May require additional setup for complex validation scenarios
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Basic text input prompt:
import prompts from 'prompts';

const response = await prompts({
  type: 'text',
  name: 'username',
  message: 'What is your username?'
});

console.log(response.username);
  1. Multiple choice prompt:
import prompts from 'prompts';

const response = await prompts({
  type: 'select',
  name: 'color',
  message: 'Pick a color',
  choices: [
    { title: 'Red', value: '#ff0000' },
    { title: 'Green', value: '#00ff00' },
    { title: 'Blue', value: '#0000ff' }
  ]
});

console.log(response.color);
  1. Password input with masking:
import prompts from 'prompts';

const response = await prompts({
  type: 'password',
  name: 'secret',
  message: 'Enter your secret password'
});

console.log('Password received');

Getting Started

To use Prompts in your Node.js project, follow these steps:

  1. Install the package:

    npm install prompts
    
  2. Import and use in your JavaScript file:

    import prompts from 'prompts';
    
    (async () => {
      const response = await prompts({
        type: 'text',
        name: 'name',
        message: 'What is your name?'
      });
    
      console.log(`Hello, ${response.name}!`);
    })();
    
  3. Run your script with Node.js:

    node your-script.js
    

Competitor Comparisons

A collection of common interactive command line user interfaces.

Pros of Inquirer.js

  • More extensive and feature-rich, offering a wider range of prompt types
  • Better support for complex, nested prompts and conditional flows
  • Larger community and ecosystem, with more plugins and extensions available

Cons of Inquirer.js

  • Larger package size and more dependencies
  • Slightly steeper learning curve due to its more comprehensive API
  • May be overkill for simpler command-line applications

Code Comparison

Prompts:

const response = await prompts([
  {
    type: 'text',
    name: 'username',
    message: 'What is your username?'
  }
]);

Inquirer.js:

const answers = await inquirer.prompt([
  {
    type: 'input',
    name: 'username',
    message: 'What is your username?'
  }
]);

Both libraries offer similar syntax for basic prompts, with Inquirer.js using input instead of text for simple text input. Inquirer.js provides more options for customization and complex scenarios, while Prompts focuses on simplicity and a smaller footprint.

Prompts is generally more lightweight and easier to get started with, making it ideal for smaller projects or when you need a quick and simple solution. Inquirer.js, on the other hand, is better suited for larger, more complex applications that require advanced prompting features and extensive customization options.

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

Pros of Enquirer

  • More extensive feature set with a wider variety of prompt types
  • Better support for complex, nested prompts and multi-step workflows
  • Highly customizable with theming and styling options

Cons of Enquirer

  • Steeper learning curve due to more complex API
  • Larger package size, which may impact load times and bundle sizes

Code Comparison

Prompts:

const { prompt } = require('prompts');

(async () => {
  const response = await prompt({
    type: 'text',
    name: 'username',
    message: 'What is your username?'
  });
})();

Enquirer:

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

(async () => {
  const response = await prompt({
    type: 'input',
    name: 'username',
    message: 'What is your username?'
  });
})();

Both libraries offer similar basic functionality for simple prompts. However, Enquirer provides more advanced features for complex scenarios, while Prompts focuses on simplicity and ease of use. The choice between them depends on the specific requirements of your project and the level of complexity you need in your command-line interfaces.

node.js command-line interfaces made easy

Pros of Commander.js

  • More comprehensive command-line interface (CLI) solution
  • Supports command-line arguments, options, and subcommands
  • Extensive documentation and large community support

Cons of Commander.js

  • Steeper learning curve for beginners
  • More complex setup for simple CLI applications
  • Larger package size

Code Comparison

Commander.js:

const program = require('commander');

program
  .version('0.1.0')
  .option('-p, --peppers', 'Add peppers')
  .option('-c, --cheese <type>', 'Add cheese')
  .parse(process.argv);

Prompts:

const prompts = require('prompts');

(async () => {
  const response = await prompts([
    { type: 'confirm', name: 'peppers', message: 'Add peppers?' },
    { type: 'text', name: 'cheese', message: 'What type of cheese?' }
  ]);
})();

Summary

Commander.js is better suited for complex CLI applications with multiple commands and options, while Prompts focuses on interactive user input. Commander.js offers more flexibility in handling command-line arguments, but Prompts provides a simpler and more intuitive way to gather user input interactively. The choice between the two depends on the specific requirements of your project and the level of complexity needed for your CLI application.

3,530

🐈 CLI app helper

Pros of meow

  • Focused on command-line argument parsing and help generation
  • Supports automatic version flag and help text generation
  • Provides a more comprehensive CLI toolkit with features like default values and option aliases

Cons of meow

  • Less interactive compared to prompts
  • May have a steeper learning curve for simple CLI applications
  • Not designed for creating interactive prompts or user input gathering

Code Comparison

meow:

#!/usr/bin/env node
import meow from 'meow';

const cli = meow(`
    Usage
      $ foo <input>

    Options
      --rainbow, -r  Include a rainbow

    Examples
      $ foo unicorns --rainbow
      🌈 unicorns 🌈
`, {
    importMeta: import.meta,
    flags: {
        rainbow: {
            type: 'boolean',
            alias: 'r'
        }
    }
});

prompts:

import prompts from 'prompts';

const response = await prompts([
  {
    type: 'text',
    name: 'username',
    message: 'What is your username?'
  },
  {
    type: 'password',
    name: 'password',
    message: 'What is your password?'
  }
]);
11,041

yargs the modern, pirate-themed successor to optimist.

Pros of yargs

  • More comprehensive command-line argument parsing
  • Supports complex nested commands and subcommands
  • Extensive documentation and large community support

Cons of yargs

  • Steeper learning curve for simple use cases
  • More verbose configuration for basic prompts
  • Larger package size and potential overhead for simpler applications

Code Comparison

prompts:

const prompts = require('prompts');

(async () => {
  const response = await prompts({
    type: 'text',
    name: 'username',
    message: 'What is your username?'
  });
  console.log(`Hello, ${response.username}!`);
})();

yargs:

const yargs = require('yargs/yargs')(process.argv.slice(2));

yargs
  .command('greet <username>', 'Greet the user', {}, (argv) => {
    console.log(`Hello, ${argv.username}!`);
  })
  .demandCommand(1)
  .parse();

prompts focuses on interactive command-line prompts, making it easier to create simple user interactions. yargs excels in parsing complex command-line arguments and creating sophisticated CLI applications with multiple commands and options. While prompts is more straightforward for basic input scenarios, yargs offers greater flexibility and power for building full-featured command-line tools.

8,977

CLI for generating, building, and releasing oclif CLIs. Built by Salesforce.

Pros of oclif

  • Full-featured CLI framework with built-in command handling and parsing
  • Supports plugins and multi-command CLIs
  • Extensive documentation and active community support

Cons of oclif

  • Steeper learning curve due to its comprehensive nature
  • More opinionated structure, which may limit flexibility for simple CLIs
  • Larger package size and potential overhead for basic applications

Code Comparison

oclif:

import {Command, flags} from '@oclif/command'

class MyCommand extends Command {
  static flags = {
    name: flags.string({char: 'n', description: 'name to print'})
  }

  async run() {
    const {flags} = this.parse(MyCommand)
    console.log(`Hello ${flags.name || 'world'}!`)
  }
}

prompts:

import prompts from 'prompts';

(async () => {
  const response = await prompts({
    type: 'text',
    name: 'name',
    message: 'What is your name?'
  });
  console.log(`Hello ${response.name || 'world'}!`);
})();

Summary

oclif is a comprehensive CLI framework suitable for complex applications, while prompts focuses on interactive command-line prompts. oclif offers more features but requires more setup, whereas prompts is simpler but limited to user input handling.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Prompts

❯ Prompts

version test downloads licenses

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

$ npm install --save prompts

This package supports Node 14 and above

split

❯ Usage

example prompt
const prompts = require('prompts');

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

  console.log(response); // => { value: 24 }
})();

See example.js for more options.

split

❯ Examples

Single Prompt

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

const prompts = require('prompts');

(async () => {
  const response = await prompts({
    type: 'text',
    name: 'meaning',
    message: 'What is the meaning of life?'
  });

  console.log(response.meaning);
})();

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.

const prompts = require('prompts');

const questions = [
  {
    type: 'text',
    name: 'username',
    message: 'What is your GitHub username?'
  },
  {
    type: 'number',
    name: 'age',
    message: 'How old are you?'
  },
  {
    type: 'text',
    name: 'about',
    message: 'Tell something about yourself',
    initial: 'Why should I?'
  }
];

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

  // => response => { username, age, about }
})();

Dynamic Prompts

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

const prompts = require('prompts');

const questions = [
  {
    type: 'text',
    name: 'dish',
    message: 'Do you like pizza?'
  },
  {
    type: prev => prev == 'pizza' ? 'text' : null,
    name: 'topping',
    message: 'Name a topping'
  }
];

(async () => {
  const response = await prompts(questions);
})();

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:

(async () => {
  const questions = [{ ... }];
  const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`);
  const response = await prompts(questions, { onSubmit });
})();

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:

(async () => {
  const questions = [{ ... }];
  const onCancel = prompt => {
    console.log('Never stop prompting!');
    return true;
  }
  const response = await prompts(questions, { onCancel });
})();

override

Type: Function

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

Example

const prompts = require('prompts');
prompts.override(require('yargs').argv);

(async () => {
  const response = await prompts([
    {
      type: 'text',
      name: 'twitter',
      message: `What's your twitter handle?`
    },
    {
      type: 'multiselect',
      name: 'color',
      message: 'Pick colors',
      choices: [
        { title: 'Red', value: '#ff0000' },
        { title: 'Green', value: '#00ff00' },
        { title: 'Blue', value: '#0000ff' }
      ],
    }
  ]);

  console.log(response);
})();

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:

const prompts = require('prompts');

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

(async () => {
  const response = await prompts([
    {
      type: 'text',
      name: 'twitter',
      message: `What's your twitter handle?`
    },
    {
      type: 'multiselect',
      name: 'color',
      message: 'Pick colors',
      choices: [
        { title: 'Red', value: '#ff0000' },
        { title: 'Green', value: '#00ff00' },
        { title: 'Blue', value: '#0000ff' }
      ],
    }
  ]);

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

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:

{
  type: String | Function,
  name: String | Function,
  message: String | Function,
  initial: String | Function | Async Function
  format: Function | Async Function,
  onRender: Function
  onState: Function
  stdin: Readable
  stdout: Writeable
}

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:

{
  type: prev => prev > 3 ? 'confirm' : null,
  name: 'confirm',
  message: (prev, values) => `Please confirm that you eat ${values.dish} times ${prev} a day?`
}

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.

{
  type: null,
  name: 'forgetme',
  message: `I'll never be shown anyway`,
}

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:

{
  type: 'number',
  name: 'price',
  message: 'Enter price',
  format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val);
}

onRender

Type: Function

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

Example:

{
  type: 'number',
  message: 'This message will be overridden',
  onRender(kleur) {
    this.msg = kleur.cyan('Enter a number');
  }
}

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
{
  type: 'text',
  name: 'value',
  message: `What's your twitter handle?`
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialstringDefault string value
stylestringRender style (default, password, invisible, emoji). Defaults to default
formatfunctionReceive user input. The returned value will be added to the response object
validatefunctionReceive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ 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
{
  type: 'password',
  name: 'value',
  message: 'Tell me a secret'
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialstringDefault string value
formatfunctionReceive user input. The returned value will be added to the response object
validatefunctionReceive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ 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
{
  type: 'invisible',
  name: 'value',
  message: 'Enter password'
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialstringDefault string value
formatfunctionReceive user input. The returned value will be added to the response object
validatefunctionReceive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ 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
{
  type: 'number',
  name: 'value',
  message: 'How old are you?',
  initial: 0,
  style: 'default',
  min: 2,
  max: 10
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialnumberDefault number value
formatfunctionReceive user input. The returned value will be added to the response object
validatefunctionReceive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
maxnumberMax value. Defaults to Infinity
minnumberMin value. Defaults to -infinity
floatbooleanAllow floating point inputs. Defaults to false
roundnumberRound float values to x decimals. Defaults to 2
incrementnumberIncrement step when using arrow keys. Defaults to 1
stylestringRender style (default, password, invisible, emoji). Defaults to default
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ back to: Prompt types


confirm(message, [initial])

Classic yes/no prompt.

Hit y or n to confirm/reject.

Example

confirm prompt
{
  type: 'confirm',
  name: 'value',
  message: 'Can you confirm?',
  initial: true
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialbooleanDefault value. Default is false
formatfunctionReceive user input. The returned value will be added to the response object
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ 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.

{
  type: 'list',
  name: 'value',
  message: 'Enter keywords',
  initial: '',
  separator: ','
}
list prompt
ParamTypeDescription
messagestringPrompt message to display
initialbooleanDefault value
formatfunctionReceive user input. The returned value will be added to the response object
separatorstringString separator. Will trim all white-spaces from start and end of string. Defaults to ','
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ 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
{
  type: 'toggle',
  name: 'value',
  message: 'Can you confirm?',
  initial: true,
  active: 'yes',
  inactive: 'no'
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialbooleanDefault value. Defaults to false
formatfunctionReceive user input. The returned value will be added to the response object
activestringText for active state. Defaults to 'on'
inactivestringText for inactive state. Defaults to 'off'
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ 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
{
  type: 'select',
  name: 'value',
  message: 'Pick a color',
  choices: [
    { title: 'Red', description: 'This option has a description', value: '#ff0000' },
    { title: 'Green', value: '#00ff00', disabled: true },
    { title: 'Blue', value: '#0000ff' }
  ],
  initial: 1
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialnumberIndex of default value
formatfunctionReceive user input. The returned value will be added to the response object
hintstringHint to display to the user
warnstringMessage to display when selecting a disabled option
choicesArrayArray of strings or choices objects [{ title, description, value, disabled }, ...]. The choice's index in the array will be used as its value if it is not specified.
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

↑ 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
{
  type: 'multiselect',
  name: 'value',
  message: 'Pick colors',
  choices: [
    { title: 'Red', value: '#ff0000' },
    { title: 'Green', value: '#00ff00', disabled: true },
    { title: 'Blue', value: '#0000ff', selected: true }
  ],
  max: 2,
  hint: '- Space to select. Return to submit'
}

Options

ParamTypeDescription
messagestringPrompt message to display
formatfunctionReceive user input. The returned value will be added to the response object
instructionsstring or booleanPrompt instructions to display
choicesArrayArray of strings or choices objects [{ title, value, disabled }, ...]. The choice's index in the array will be used as its value if it is not specified.
optionsPerPagenumberNumber of options displayed per page (default: 10)
minnumberMin select - will display error
maxnumberMax select
hintstringHint to display to the user
warnstringMessage to display when selecting a disabled option
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

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
{
  type: 'autocomplete',
  name: 'value',
  message: 'Pick your favorite actor',
  choices: [
    { title: 'Cage' },
    { title: 'Clooney', value: 'silver-fox' },
    { title: 'Gyllenhaal' },
    { title: 'Gibson' },
    { title: 'Grant' }
  ]
}

Options

ParamTypeDescription
messagestringPrompt message to display
formatfunctionReceive user input. The returned value will be added to the response object
choicesArrayArray of auto-complete choices objects [{ title, value }, ...]
suggestfunctionFilter function. Defaults to sort by title property. suggest should always return a promise. Filters using title by default
limitnumberMax number of results to show. Defaults to 10
stylestringRender style (default, password, invisible, emoji). Defaults to 'default'
initialstring | numberDefault initial value
clearFirstbooleanThe first ESCAPE keypress will clear the input
fallbackstringFallback message when no match is found. Defaults to initial value if provided
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with three properties: value, aborted and exited

Example on what a suggest function might look like:

const suggestByTitle = (input, choices) =>
    Promise.resolve(choices.filter(i => i.title.slice(0, input.length) === input))

↑ 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
{
  type: 'date',
  name: 'value',
  message: 'Pick a date',
  initial: new Date(1997, 09, 12),
  validate: date => date > Date.now() ? 'Not in the future' : true
}

Options

ParamTypeDescription
messagestringPrompt message to display
initialdateDefault date
localesobjectUse to define custom locales. See below for an example.
maskstringThe format mask of the date. See below for more information.
Default: YYYY-MM-DD HH:mm:ss
validatefunctionReceive user input. Should return true if the value is valid, and an error message String otherwise. If false is returned, a default error message is shown
onRenderfunctionOn render callback. Keyword this refers to the current prompt
onStatefunctionOn state change callback. Function signature is an object with two properties: value and aborted

Default locales:

{
  months: [
    'January', 'February', 'March', 'April',
    'May', 'June', 'July', 'August',
    'September', 'October', 'November', 'December'
  ],
  monthsShort: [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  ],
  weekdays: [
    'Sunday', 'Monday', 'Tuesday', 'Wednesday',
    'Thursday', 'Friday', 'Saturday'
  ],
  weekdaysShort: [
    'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
  ]
}

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

MIT © Terkel Gjervig

NPM DownloadsLast 30 Days