prompts

repository·master·Indexed 27 days ago

https://github.com/terkelg/prompts

A lightweight, promise-based Node.js library for creating interactive CLI prompts. Version 2.4.2 supports Node 14 and above. It features a variety of prompt types including text, password, number, confirm, list, toggle, select, multiselect, autocomplete, and date. The library supports dynamic prompt chains, input validation, formatting, and programmatic response injection via inject() and override() methods.

Tokens
4.4K
Snippets
20
Records
26
Agent score
83%

What's inside prompts

  1. Use prompts for interactive CLI input

    master

    Import prompts and call the main function with a prompt object or an array of prompt objects. The function returns a Promise that resolves to an object containing the user's responses, keyed by the name property of each prompt.

    const prompts = require('prompts');
    
    (async () => {
      const response = await prompts({
        type: 'number',
        name: 'age',
        message: 'How old are you?',
        validate: value => value < 18 ? `Nightclub is 18+ only` : true
      });
    
      console.log(response); // => { age: 24 }
    })();
  2. Implement dynamic prompts

    master

    Prompt properties like type can be functions. If a type function returns a falsy value, the prompt is skipped. This allows for conditional logic based on previous answers.

    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);
    })();
  3. Create a prompt chain

    master

    Pass an array of prompt objects to prompts() to execute a sequence of questions. Ensure each prompt has a unique name to avoid overwriting values in the resulting response object.

    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 }
    })();
  4. Pre-answer questions with prompts.override()

    master

    Use prompts.override(values) to automatically fill in answers. This is useful for integrating with command-line argument parsers like yargs.

    const prompts = require('prompts');
    prompts.override(require('yargs').argv);
    
    (async () => {
      const response = await prompts([
        {
          type: 'text',
          name: 'twitter',
          message: `What's your twitter handle?`
        }
      ]);
    })();
  5. Programmatically inject responses with prompts.inject()

    master

    Use prompts.inject(values) to prepare responses ahead of time, primarily for testing. If an injected value is an Error, it simulates a user cancellation/exit.

    const prompts = require('prompts');
    
    // Injecting a single value and an array of values for multiple questions
    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: '#0000ff' },
            { title: 'Blue', value: '#0000ff' }
          ],
        }
      ]);
    
      // => { twitter: 'terkelg', color: [ '#ff0000', '#0000ff' ] }
    })();
  6. Configure onSubmit and onCancel callbacks

    master

    The prompts(prompts, options) function accepts an options object with two lifecycle callbacks:

    • onSubmit(prompt, answer, answers): Invoked after each submission. Returning true quits the chain and returns collected responses. Async supported.
    • onCancel(prompt, answers): Invoked when the user cancels. Returning true prevents the loop from aborting and continues prompting.
    // onSubmit example
    const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`);
    const response = await prompts(questions, { onSubmit });
    
    // onCancel example
    const onCancel = prompt => {
      console.log('Never stop prompting!');
      return true;
    }
    const response = await prompts(questions, { onCancel });
  7. Configure Prompt Object properties

    master

    A prompt object defines the question. Most properties can be functions with the signature (prev, values, prompt), where prev is the previous answer, values is the full response object, and prompt is the previous prompt object.

    Key properties:

    • type: String | Function. If falsy, the prompt is skipped.
    • name: String | Function. The key in the response object.
    • message: String | Function. The text displayed to the user.
    • initial: String | Function | Async Function. Default value.
    • format: Function. Transforms the input before adding it to the response. Signature: (val, values).
    • onRender: Function. Callback when rendering. Receives kleur as the first argument.
    • onState: Function. Callback on state change. Receives state object { value, aborted }.
    • stdin / stdout: Stream. Custom input/output streams (defaults to process.stdin/process.stdout).
    {
      type: 'number',
      name: 'price',
      message: 'Enter price',
      format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val);
    }
  8. Override answers using override()

    master

    The override(answers) function allows you to force specific answers for questions based on their name. This takes precedence over user input and injected values.

    • answers must be an object where keys match the name property of the question objects.
    • If an override is found for a question name, the format and validate logic is still applied to the overridden value.
  9. Use exported prompt elements

    master
    The prompts package provides several specialized prompt elements for different types of user input. You can import these elements to build interactive CLI interfaces. Available prompt types include text, selection, toggles, dates, numbers, multiselect, autocomplete, and confirmation prompts.
  10. Prompt for a series of questions with prompt()

    master

    The prompt() function handles a single question object or an array of question objects. It iterates through the questions, manages user input via specific prompt types, and returns an object containing the collected answers.

    Key features:

    • Dynamic Types: If type is a function, it is evaluated with the current answer, answers (all previous answers), and the question object to determine the prompt type.
    • Dynamic Properties: Any property in the question object that is not in the passOn list (suggest, format, onState, validate, onRender, type) can be a function. These functions are invoked with (answer, answers, lastPrompt) to allow dynamic configuration.
    • Validation: If a validate function is provided, it must return true for the answer to be accepted.
    • Formatting: A format function can be used to transform the answer before it is stored.
    • Callbacks: Supports onSubmit(question, answer, answers) and onCancel(question, answers) callbacks.
    • Termination: If onSubmit returns a truthy value, the prompting process stops and returns the current answers.