世娱网
您的当前位置:首页inquirer.js一个用户与命令行交互的工具详解

inquirer.js一个用户与命令行交互的工具详解

来源:世娱网


一. 使用

0. 语法结构

const inquirer = require('inquirer');

const promptList = [
 // 具体交互内容
];

inquirer.prompt(promptList).then(answers => {
 console.log(answers); // 返回的结果
})

1. input

const promptList = [{
 type: 'input',
 message: '设置一个用户名:',
 name: 'name',
 default: "test_user" // 默认值
},{
 type: 'input',
 message: '请输入手机号:',
 name: 'phone',
 validate: function(val) {
 if(val.match(/\d{11}/g)) { // 校验位数
 return val;
 }
 return "请输入11位数字";
 }
}];

效果:

2. confirm

const promptList = [{
 type: "confirm",
 message: "是否使用监听?",
 name: "watch",
 prefix: "前缀"
},{
 type: "confirm",
 message: "是否进行文件过滤?",
 name: "filter",
 suffix: "后缀",
 when: function(answers) { // 当watch为true的时候才会提问当前问题
 return answers.watch
 }
}];

效果:

 

3. list

const promptList = [{
 type: 'list',
 message: '请选择一种水果:',
 name: 'fruit',
 choices: [
 "Apple",
 "Pear",
 "Banana"
 ],
 filter: function (val) { // 使用filter将回答变为小写
 return val.toLowerCase();
 }
}];

效果:

 

4. rawlist

const promptList = [{
 type: 'rawlist',
 message: '请选择一种水果:',
 name: 'fruit',
 choices: [
 "Apple",
 "Pear",
 "Banana"
 ]
}];

效果:

5. expand

const promptList = [{
 type: "expand",
 message: "请选择一种水果:",
 name: "fruit",
 choices: [
 {
 key: "a",
 name: "Apple",
 value: "apple"
 },
 {
 key: "O",
 name: "Orange",
 value: "orange"
 },
 {
 key: "p",
 name: "Pear",
 value: "pear"
 }
 ]
}];

效果:

 

6. checkbox

const promptList = [{
 type: "checkbox",
 message: "选择颜色:",
 name: "color",
 choices: [
 {
 name: "red"
 },
 new inquirer.Separator(), // 添加分隔符
 {
 name: "blur",
 checked: true // 默认选中
 },
 {
 name: "green"
 },
 new inquirer.Separator("--- 分隔符 ---"), // 自定义分隔符
 {
 name: "yellow"
 }
 ]
}];
// 或者下面这样
const promptList = [{
 type: "checkbox",
 message: "选择颜色:",
 name: "color",
 choices: [
 "red",
 "blur",
 "green",
 "yellow"
 ],
 pageSize: 2 // 设置行数
}];

效果:

 

7. password

const promptList = [{
 type: "password", // 密码为密文输入
 message: "请输入密码:",
 name: "pwd"
}];

效果:

8. editor

const promptList = [{
 type: "editor",
 message: "请输入备注:",
 name: "editor"
}];

效果:

 

写在后面:

显示全文