Inquirer.js

一个使用界面进行交互的命令行集合
4.0以上的版本只支持node 6以上的,node4请使用3.x

目标和理念(hilosophy)

努力去做一个容易的 嵌入式的(embeddable) 和优美的命令行界面
应该简化一下的过程:
-提供一个错误回调
-询问
-解析(parsing )输入
-验证答案
-管理层次提示

导入(Installation)

npm install inquirer
var inquirer = require(‘inquirer‘);inquirer .prompt([ /* Pass your questions in here */ ]) .then(answers => { // Use user feedback for... whatever!! });

案例位置

node packages/inquirer/examples/pizza.jsnode packages/inquirer/examples/checkbox.js# etc...

方法

inquirer.prompt(questions) -> promise
调出提示界面
-questions (数组类型)包含一个Question 对象
-返回一个promise

inquirer.registerPrompt(name, prompt)
使用name注册prompt
-name:prompt的名字
-prompt:prompt事件

inquirer.createPromptModule() -> prompt function
创建一个自包含的问答模块,当你复写或者添加一个新的问答模块时,你不希望影响其他模块,你也可以这么做

var prompt = inquirer.createPromptModule(); prompt(questions).then(/* ... */);

object

*Question*

一个question object是一个包含于问题有关系的hash
type(字符串):prompt的类型,默认是input,值列表:input, confirm, list, rawlist, expand, checkbox, password, editor
name(string):在下面答案对象中存储用户输入的答案的标志名
message(字符串|函数):输出的问题,如果是一个函数 第一个参数默认是用户输入的答案,默认值是name
default(String|Number|Boolean|Array|Function):如果用户没有输入任何值,这里存放默认值,或者是一个函数返回一个默认值,如果被定义为一个函数,第一个参数默认是用户的输入值
choices(Array|Function):一个数组 或者是一个返回数组的函数,如果被定义成函数 第一个参数是用户的输入值,数组可以是一个字符串数组,或者是一个字段数组,字典的属性有name、value、properties,
validate(Function):一个接受用户输入的方法,如果验证成功的话 应该返回true,如果失败的话,需要返回一个字符串,字符串是错误信息,如果你返回false的话 我们就会使用默认错误信息
filter(Function):一个将用户输入的进行过滤的方法
pageSize(Number):更改当使用list rawList expand 或者checkbox时候应该使用的行数

Answers

在每一个提示中包含答案的散列
-Key :question object的名称
-Value :((他的类型取决于问题)
-confirm(boolern)
-input 用户输入的信息(如果使用了filter,则进行过滤)
-rawlist list:用户选择的值

分隔符(Separator)
一个分隔符可以被添加进choices 数组:

// In the question objectchoices: [ "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

相关文章