Make writing a habit together! This is the sixth day of my participation in the “Gold Digging Day New Plan ยท April More text Challenge”. Click here for more details.

Basic usage of inquirer

What is the inquirer. Js

Inquirer. Js is a collection of tools for implementing command-line interactive interfaces. It helps us to realize interactive communication with the user, such as asking the user a question, the user gives us an answer, we do something according to the user’s answer.

It contains the following features:

  • Users can be asked questions
  • Parse the answers entered by the user
  • Validate user input
  • Provides error callbacks

The installation

npm i inquirer -S
Copy the code

use

/ / into the inquirer
const inquirer = require('inquirer');
/ / start the inquirer
inquirer
  // Interactive content
  .prompt([
  ])
  // The callback to collect the user's answers is stored here as key-value pairs
  .then((answers) = >{})// Catch an error callback
  .catch((error) = >{});Copy the code

Default, choices, validate, filter, and the when the value of function, can be an asynchronous invocation, can also return a Promise or use this. Async () method to obtain a callback, final value is then used to invoke it.

{
  filter() {
    return new Promise(a); },validate: function (input) {
    var done = this.async();
    setTimeout(function() {
      if (typeofinput ! = ='number') {
        done('You need to provide a number');
        return;
      }
      done(null.true);
    }, 3000); }}Copy the code

attribute

This is just an introduction for now, and I’ll show you how to use all the attributes in the code.

type

Indicates the type of question, including:

  • input
  • number
  • confirm
  • list
  • rawlist
  • expand
  • checkbox
  • password
  • editor

name

A variable that stores the answer to the current question;

message

Description of the problem;

default

The default value;

choices

The list option, available under certain types, and containing a separator;

validate

Validates the user’s answer, proceeding down only if true is returned;

filter

The user’s answers are filtered and the processed value is returned to modify the value submitted by the user.

transformer

Processing the display effect of the user’s answer (e.g. changing the font or background color of the answer), but will not affect the content of the final answer;

when

Judge whether the current question needs to be answered based on the answers to the previous questions.

pageSize

Modify the number of render lines for certain types.

prefix

Modify the default message prefix;

suffix

Modify the default message suffix;

mask

Change the display mode when type is password.

Interaction types

input

Input interaction, the complete code is shown below, but I will demonstrate by adding attributes one by one.

inquirer
  .prompt([
    {
      type: 'input'.message: 'Please enter your name'.name: 'name'.default: A Warbler's Tail.validate: (answer) = > {
        if (answer.length < 2) {
          return 'Name must not be less than two characters';
        }
        console.log();
        return true;
      },
      transformer: (a) = > {
        return 'The most handsome people are:${a}`;
      },
      filter: (a) = > {
        return 'The most handsome people are:${a}`;
      },
      prefix: '๐ŸŸข'.suffix: '๐ŸŸก',
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

Currently, only the following attributes are set

  • Type: interaction type, input class
  • Message: Problem description, displayed on the command line
  • Name: The field value that will be assigned user input to the field defined by this property

Next, we set a default property. You can see the parentheses at the end of the question, and inside the parentheses is the default value that we set. If you enter nothing and press enter, the default value will be used.

  • Default: indicates the default value

Next, we set a validate attribute to verify the answer. If the answer does not meet the criteria, we will be prompted to pass.

  • Validate: Verifies the user’s answer, and only returnstrueThe rest of the content will be returned as a prompt output in the page

Next we set up a transformer property that modifies the display of the answer content, but not the actual answer. As you can see, the final callback output is still “a streamer”, but the screen displays “Most handsome: a streamer”.

  • Transformer: Process the display of the user’s answer without affecting the content of the final answer

Next we set a filter property, which modifies the actual answer. You can see that we typed “a warbler”, but the callback output was “the most handsome person is: a warbler”.

  • Filter: The user answers are filtered and the processed value is returned. The value submitted by the user is modified

Next we set the prefix and suffix separately. As you can see, I added a green circle to the front of the question and a yellow circle to the end of the question.

  • The prefix: modifymessageThe default prefix
  • Suffix: modifymessageThe default suffix

number

For digital interaction, input is automatically converted to number or NaN if it is not a number.

inquirer
  .prompt([
    {
      type: 'number'.message: 'Please enter age'.name: 'age',
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

PS: Here you can usevalidateProperty to validate user input.

confirm

Confirm the interaction. Default values are displayed in uppercase letters on the screen.

inquirer
  .prompt([
    {
      type: 'confirm'.message: 'Single? '.name: 'single'.default: 'true',
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

list

List selection interaction, where two new properties are involved.

inquirer
  .prompt([
    {
      type: 'list'.message: 'Please choose your wife.'.name: 'wife'.default: 0.choices: [{value: 1.name: 'Zhao Jinmai'}, {value: 2.name: 'Tan Song Yun'}, {value: 3.name: 'MAO Xiaotong'}, {value: 4.name: 'Niigaki Noyi'],},pageSize: 2,
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code
  • Choices: A list of choicestypeIs available and can contain a delimiter (separator )

If a delimiter is set, the options are split.

  • PageSize: Modify somethingtypeNumber of rendered lines under type

If pageSize is set, the rest of the options are hidden and toggled with the up and down keys.

rawlist

This is similar to a list, except that you can select it by entering an index, or by pressing up or down.

inquirer
  .prompt([
    {
      type: 'rawlist'.message: 'Please choose your wife.'.name: 'wife'.default: 0.choices: [{value: 1.name: 'Zhao Jinmai'}, {value: 2.name: 'Tan Song Yun'}, {value: 3.name: 'MAO Xiaotong'}, {value: 4.name: 'Niigaki Noyi',
        },
      ],
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

expand

This is similar to list, providing shorthand, but the syntax is a bit different. Type H to view all options.

inquirer
  .prompt([
    {
      type: 'expand'.message: 'Please select a color'.name: 'color'.default: 'R'.choices: [{key: 'R'.value: 'red'}, {key: 'G'.value: 'green'}, {key: 'B'.value: 'blue',
        },
      ],
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

checkbox

Multi-select interaction, select by space, enter for confirmation, and select by default by adding checked: True to the options. Select all through A and reverse through I.

inquirer
  .prompt([
    {
      type: 'checkbox'.message: 'Please choose your wives :'.name: 'wifes'.choices: [{value: 1.name: 'Zhao Jinmai'.checked: true}, {value: 2.name: 'Tan Song Yun'}, {value: 3.name: 'MAO Xiaotong'}, {value: 4.name: 'Niigaki Noyi',
        },
      ],
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

password

In password interaction, users can hide the input content and modify the display mode through the mask attribute. One way is to hide the input, and the other way is to replace the input with *.

inquirer
  .prompt([
    {
      type: 'password'.message: 'Please enter password 1:'.name: 'password1'}, {type: 'password'.message: 'Please enter password 2:'.name: 'password2'.mask: true,
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

editor

Open a text editor for typing something complex. Press Enter to open the editor.

when

Finally, let’s look at the use of the when attribute.

The callback argument to WHEN is the answer to all the previous questions, and only when the return value is true will an interaction of the type WHEN occur.

inquirer
  .prompt([
    {
      type: 'confirm'.message: 'Single? '.name: 'single'.default: true}, {type: 'confirm'.message: 'Do you need a girlfriend? '.name: 'girl'.when: function (answers) {
        // The current question is asked when single is true
        return answers.single;
      },
    },
  ])
  .then((answers) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ answers', answers);
  })
  .catch((error) = > {
    console.log('๐Ÿš€ ๐Ÿš€ ~ error', error);
  });
Copy the code

The inquirer’s usage is relatively simple, and at this point it should cover most of the interaction needs of everyday development.