Fork me on GitHub

inquirer.js-常见的交互式命令行用户接口的集合

创建交互式命令行用户接口

github地址: https://github.com/SBoudrias/Inquirer.js

Installation

1
npm install inquirer
1
2
3
4
var inquirer = require('inquirer');
inquirer.prompt([/* Pass your questions in here */]).then(function (answers) {
// Use user feedback for... whatever!!
});

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Pizza delivery prompt example
* run example by writing `node pizza.js` in your console
*/

'use strict';
var inquirer = require('..');

console.log('Hi, welcome to Node Pizza');

var questions = [
{
type: 'confirm',
name: 'toBeDelivered',
message: 'Is this for delivery?',
default: false
},
{
type: 'input',
name: 'phone',
message: 'What\'s your phone number?',
validate: function (value) {
var pass = value.match(/^([01]{1})?[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i);
if (pass) {
return true;
}

return 'Please enter a valid phone number';
}
},
{
type: 'list',
name: 'size',
message: 'What size do you need?',
choices: ['Large', 'Medium', 'Small'],
filter: function (val) {
return val.toLowerCase();
}
},
{
type: 'input',
name: 'quantity',
message: 'How many do you need?',
validate: function (value) {
var valid = !isNaN(parseFloat(value));
return valid || 'Please enter a number';
},
filter: Number
},
{
type: 'expand',
name: 'toppings',
message: 'What about the toppings?',
choices: [
{
key: 'p',
name: 'Pepperoni and cheese',
value: 'PepperoniCheese'
},
{
key: 'a',
name: 'All dressed',
value: 'alldressed'
},
{
key: 'w',
name: 'Hawaiian',
value: 'hawaiian'
}
]
},
{
type: 'rawlist',
name: 'beverage',
message: 'You also get a free 2L beverage',
choices: ['Pepsi', '7up', 'Coke']
},
{
type: 'input',
name: 'comments',
message: 'Any comments on your purchase experience?',
default: 'Nope, all good!'
},
{
type: 'list',
name: 'prize',
message: 'For leaving a comment, you get a freebie',
choices: ['cake', 'fries'],
when: function (answers) {
return answers.comments !== 'Nope, all good!';
}
}
];

inquirer.prompt(questions).then(function (answers) {
console.log('\nOrder receipt:');
console.log(JSON.stringify(answers, null, ' '));
});

运行效果:

坚持原创技术分享,您的支持将鼓励我继续创作!