inquirer命令行表单

478 阅读2分钟

介绍

安装

npm install inquirer

模板解析

var inquirer = require('inquirer');
inquirer
  .prompt([
    /* Pass your questions in here */
  ])
  .then(answers => {
    // Use user feedback for... whatever!!
  })
  .catch(error => {
    if(error.isTtyError) {
      // Prompt couldn't be rendered in the current environment
    } else {
      // Something else went wrong
    }
  });

方法

inquirer.prompt(questions, answers) -> promise

inquirer.registerPrompt(name, prompt)

inquirer.createPromptModule() -> prompt function

var prompt = inquirer.createPromptModule();

prompt(questions).then(/* ... */);

question

  • type: (String) Type of the prompt. Defaults: input - Possible values: input, number, confirm, list, rawlist, expand, checkbox, password, editor
  • name: (String) The name to use when storing the answer in the answers hash. If the name contains periods, it will define a path in the answers hash.
  • message: (String|Function) The question to print. If defined as a function, the first parameter will be the current inquirer session answers. Defaults to the value of name (followed by a colon).
  • default: (String|Number|Boolean|Array|Function) Default value(s) to use if nothing is entered, or a function that returns the default value(s). If defined as a function, the first parameter will be the current inquirer session answers.
  • choices: (Array|Function) Choices array or a function returning a choices array. If defined as a function, the first parameter will be the current inquirer session answers. Array values can be simple numbers, strings, or objects containing a name (to display in list), a value (to save in the answers hash), and a short (to display after selection) properties. The choices array can also contain a Separator.
  • validate: (Function) Receive the user input and answers hash. Should return true if the value is valid, and an error message (String) otherwise. If false is returned, a default error message is provided.
  • filter: (Function) Receive the user input and answers hash. Returns the filtered value to be used inside the program. The value returned will be added to the Answers hash. transformer: (Function) Receive the user input, answers hash and option flags, and return a transformed value to display to the user. The transformation only impacts what is shown while editing. It does not modify the answers hash.
  • when: (Function, Boolean) Receive the current user answers hash and should return true or false depending on whether or not this question should be asked. The value can also be a simple boolean. pageSize: (Number) Change the number of lines that will be rendered when using list, rawList, expand or checkbox.
  • prefix: (String) Change the default prefix message.
  • suffix: (String) Change the default suffix message.
  • askAnswered: (Boolean) Force to prompt the question if the answer already exists.
  • loop: (Boolean) Enable list looping. Defaults: true
{
  /* Preferred way: with promise */
  filter() {
    return new Promise(/* etc... */);
  },

  /* Legacy way: with this.async */
  validate: function (input) {
    // Declare function as asynchronous, and save the done callback
    var done = this.async();

    // Do async stuff
    setTimeout(function() {
      if (typeof input !== 'number') {
        // Pass the return value in the done callback
        done('You need to provide a number');
        return;
      }
      // Pass the return value in the done callback
      done(null, true);
    }, 3000);
  }
}

Answers

  • Key The name property of the question object
  • Value (Depends on the prompt)
    • confirm: (Boolean)
    • input : User input (filtered if filter is defined) (String)
    • number: User input (filtered if filter is defined) (Number)
    • rawlist, list : Selected choice value (or name if no value specified) (String)

Separator

// In the question object
choices: [ "Choice A", new inquirer.Separator(), "choice B" ]

// Which'll be displayed this way
[?] What do you want to do?
 > Order a pizza
   Make a reservation
   --------
   Ask opening hours
   Talk to the receptionist

Prompt types

  • List - {type: 'list'}
  • Raw List - {type: 'rawlist'}
  • Expand - {type: 'expand'}
  • heckbox - {type: 'checkbox'}
  • Confirm - {type: 'confirm'}
  • Input - {type: 'input'}
  • Input - {type: 'number'}
  • Password - {type: 'password'}
  • Editor - {type: 'editor'}

用户接口和布局

Bottom Bar - inquirer.ui.BottomBar

ar ui = new inquirer.ui.BottomBar();

// pipe a Stream to the log zone
outputStream.pipe(ui.log);

// Or simply write output
ui.log.write('something just happened.');
ui.log.write('Almost over, standby!');

// During processing, update the bottom bar content to display a loader
// or output a progress bar, etc
ui.updateBottomBar('new bottom bar content');

反应界面

  • 步骤设定
var prompts = new Rx.Subject();
inquirer.prompt(prompts);

// At some point in the future, push new questions
prompts.next({
  /* question... */
});
prompts.next({
  /* question... */
});

// When you're done
prompts.complete();
  • 回调
inquirer.prompt(prompts).ui.process.subscribe(onEachAnswer, onError, onComplete);

插件

  • autocomplete
  • checkbox-plus
  • inquirer-date-prompt
  • datetime
  • inquirer-select-line
  • inquirer-fuzzy-path
  • inquirer-emoji
  • inquirer-chalk-pipe
  • inquirer-search-checkbox
  • inquirer-search-list
  • inquirer-prompt-suggest
  • inquirer-s3
  • inquirer-autosubmit-prompt
  • inquirer-file-tree-selection-prompt
  • inquirer-table-prompt