UNPKG

20.7 kBMarkdownView Raw
1<img width="75px" height="75px" align="right" alt="Inquirer Logo" src="https://raw.githubusercontent.com/SBoudrias/Inquirer.js/master/assets/inquirer_readme.svg?sanitize=true" title="Inquirer.js"/>
2
3# Inquirer.js
4
5[![npm](https://badge.fury.io/js/inquirer.svg)](http://badge.fury.io/js/inquirer)
6[![Coverage Status](https://codecov.io/gh/SBoudrias/Inquirer.js/branch/master/graph/badge.svg)](https://codecov.io/gh/SBoudrias/Inquirer.js)
7[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FSBoudrias%2FInquirer.js.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2FSBoudrias%2FInquirer.js?ref=badge_shield)
8
9A collection of common interactive command line user interfaces.
10
11## Table of Contents
12
131. [Documentation](#documentation)
14 1. [Installation](#installation)
15 2. [Examples](#examples)
16 3. [Methods](#methods)
17 4. [Objects](#objects)
18 5. [Questions](#questions)
19 6. [Answers](#answers)
20 7. [Separator](#separator)
21 8. [Prompt Types](#prompt)
222. [User Interfaces and Layouts](#layouts)
23 1. [Reactive Interface](#reactive)
243. [Support](#support)
254. [Known issues](#issues)
265. [News](#news)
276. [Contributing](#contributing)
287. [License](#license)
298. [Plugins](#plugins)
30
31## Goal and Philosophy
32
33**`Inquirer.js`** strives to be an easily embeddable and beautiful command line interface for [Node.js](https://nodejs.org/) (and perhaps the "CLI [Xanadu](https://en.wikipedia.org/wiki/Citizen_Kane)").
34
35**`Inquirer.js`** should ease the process of
36
37- providing _error feedback_
38- _asking questions_
39- _parsing_ input
40- _validating_ answers
41- managing _hierarchical prompts_
42
43> **Note:** **`Inquirer.js`** provides the user interface and the inquiry session flow. If you're searching for a full blown command line program utility, then check out [commander](https://github.com/visionmedia/commander.js), [vorpal](https://github.com/dthree/vorpal) or [args](https://github.com/leo/args).
44
45## [Documentation](#documentation)
46
47<a name="documentation"></a>
48
49### Installation
50
51<a name="installation"></a>
52
53```shell
54npm install inquirer
55```
56
57```javascript
58var inquirer = require('inquirer');
59inquirer
60 .prompt([
61 /* Pass your questions in here */
62 ])
63 .then((answers) => {
64 // Use user feedback for... whatever!!
65 })
66 .catch((error) => {
67 if (error.isTtyError) {
68 // Prompt couldn't be rendered in the current environment
69 } else {
70 // Something else went wrong
71 }
72 });
73```
74
75<a name="examples"></a>
76
77### Examples (Run it and see it)
78
79Check out the [`packages/inquirer/examples/`](https://github.com/SBoudrias/Inquirer.js/tree/master/packages/inquirer/examples) folder for code and interface examples.
80
81```shell
82node packages/inquirer/examples/pizza.js
83node packages/inquirer/examples/checkbox.js
84# etc...
85```
86
87### Methods
88
89<a name="methods"></a>
90
91#### `inquirer.prompt(questions, answers) -> promise`
92
93Launch the prompt interface (inquiry session)
94
95- **questions** (Array) containing [Question Object](#question) (using the [reactive interface](#reactive-interface), you can also pass a `Rx.Observable` instance)
96- **answers** (object) contains values of already answered questions. Inquirer will avoid asking answers already provided here. Defaults `{}`.
97- returns a **Promise**
98
99#### `inquirer.registerPrompt(name, prompt)`
100
101Register prompt plugins under `name`.
102
103- **name** (string) name of the this new prompt. (used for question `type`)
104- **prompt** (object) the prompt object itself (the plugin)
105
106#### `inquirer.createPromptModule() -> prompt function`
107
108Create a self contained inquirer module. If you don't want to affect other libraries that also rely on inquirer when you overwrite or add new prompt types.
109
110```js
111var prompt = inquirer.createPromptModule();
112
113prompt(questions).then(/* ... */);
114```
115
116### Objects
117
118<a name="objects"></a>
119
120#### Question
121
122<a name="questions"></a>
123A question object is a `hash` containing question related values:
124
125- **type**: (String) Type of the prompt. Defaults: `input` - Possible values: `input`, `number`, `confirm`,
126 `list`, `rawlist`, `expand`, `checkbox`, `password`, `editor`
127- **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.
128- **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).
129- **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.
130- **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.
131 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`](#separator).
132- **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.
133- **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.
134- **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.
135- **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.
136- **pageSize**: (Number) Change the number of lines that will be rendered when using `list`, `rawList`, `expand` or `checkbox`.
137- **prefix**: (String) Change the default _prefix_ message.
138- **suffix**: (String) Change the default _suffix_ message.
139- **askAnswered**: (Boolean) Force to prompt the question if the answer already exists.
140- **loop**: (Boolean) Enable list looping. Defaults: `true`
141
142`default`, `choices`(if defined as functions), `validate`, `filter` and `when` functions can be called asynchronously. Either return a promise or use `this.async()` to get a callback you'll call with the final value.
143
144```javascript
145{
146 /* Preferred way: with promise */
147 filter() {
148 return new Promise(/* etc... */);
149 },
150
151 /* Legacy way: with this.async */
152 validate: function (input) {
153 // Declare function as asynchronous, and save the done callback
154 var done = this.async();
155
156 // Do async stuff
157 setTimeout(function() {
158 if (typeof input !== 'number') {
159 // Pass the return value in the done callback
160 done('You need to provide a number');
161 return;
162 }
163 // Pass the return value in the done callback
164 done(null, true);
165 }, 3000);
166 }
167}
168```
169
170### Answers
171
172<a name="answers"></a>
173A key/value hash containing the client answers in each prompt.
174
175- **Key** The `name` property of the _question_ object
176- **Value** (Depends on the prompt)
177 - `confirm`: (Boolean)
178 - `input` : User input (filtered if `filter` is defined) (String)
179 - `number`: User input (filtered if `filter` is defined) (Number)
180 - `rawlist`, `list` : Selected choice value (or name if no value specified) (String)
181
182### Separator
183
184<a name="separator"></a>
185A separator can be added to any `choices` array:
186
187```
188// In the question object
189choices: [ "Choice A", new inquirer.Separator(), "choice B" ]
190
191// Which'll be displayed this way
192[?] What do you want to do?
193 > Order a pizza
194 Make a reservation
195 --------
196 Ask opening hours
197 Talk to the receptionist
198```
199
200The constructor takes a facultative `String` value that'll be use as the separator. If omitted, the separator will be `--------`.
201
202Separator instances have a property `type` equal to `separator`. This should allow tools façading Inquirer interface from detecting separator types in lists.
203
204<a name="prompt"></a>
205
206### Prompt types
207
208---
209
210> **Note:**: _allowed options written inside square brackets (`[]`) are optional. Others are required._
211
212#### List - `{type: 'list'}`
213
214Take `type`, `name`, `message`, `choices`[, `default`, `filter`, `loop`] properties.
215(Note: `default` must be set to the `index` or `value` of one of the entries in `choices`)
216
217![List prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/list.svg)
218
219---
220
221#### Raw List - `{type: 'rawlist'}`
222
223Take `type`, `name`, `message`, `choices`[, `default`, `filter`, `loop`] properties.
224(Note: `default` must be set to the `index` of one of the entries in `choices`)
225
226![Raw list prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/rawlist.svg)
227
228---
229
230#### Expand - `{type: 'expand'}`
231
232Take `type`, `name`, `message`, `choices`[, `default`] properties.
233Note: `default` must be the `index` of the desired default selection of the array. If `default` key not provided, then `help` will be used as default choice
234
235Note that the `choices` object will take an extra parameter called `key` for the `expand` prompt. This parameter must be a single (lowercased) character. The `h` option is added by the prompt and shouldn't be defined by the user.
236
237See `examples/expand.js` for a running example.
238
239![Expand prompt closed](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/expand-y.svg)
240![Expand prompt expanded](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/expand-d.svg)
241
242---
243
244#### Checkbox - `{type: 'checkbox'}`
245
246Take `type`, `name`, `message`, `choices`[, `filter`, `validate`, `default`, `loop`] properties. `default` is expected to be an Array of the checked choices value.
247
248Choices marked as `{checked: true}` will be checked by default.
249
250Choices whose property `disabled` is truthy will be unselectable. If `disabled` is a string, then the string will be outputted next to the disabled choice, otherwise it'll default to `"Disabled"`. The `disabled` property can also be a synchronous function receiving the current answers as argument and returning a boolean or a string.
251
252![Checkbox prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/checkbox.svg)
253
254---
255
256#### Confirm - `{type: 'confirm'}`
257
258Take `type`, `name`, `message`, [`default`] properties. `default` is expected to be a boolean if used.
259
260![Confirm prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/confirm.svg)
261
262---
263
264#### Input - `{type: 'input'}`
265
266Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `transformer`] properties.
267
268![Input prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/input.svg)
269
270---
271
272#### Input - `{type: 'number'}`
273
274Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `transformer`] properties.
275
276---
277
278#### Password - `{type: 'password'}`
279
280Take `type`, `name`, `message`, `mask`,[, `default`, `filter`, `validate`] properties.
281
282![Password prompt](https://cdn.rawgit.com/SBoudrias/Inquirer.js/28ae8337ba51d93e359ef4f7ee24e79b69898962/assets/screenshots/password.svg)
283
284---
285
286Note that `mask` is required to hide the actual user input.
287
288#### Editor - `{type: 'editor'}`
289
290Take `type`, `name`, `message`[, `default`, `filter`, `validate`, `postfix`] properties
291
292Launches an instance of the users preferred editor on a temporary file. Once the user exits their editor, the contents of the temporary file are read in as the result. The editor to use is determined by reading the $VISUAL or $EDITOR environment variables. If neither of those are present, notepad (on Windows) or vim (Linux or Mac) is used.
293
294The `postfix` property is useful if you want to provide an extension.
295
296<a name="layouts"></a>
297
298### Use in Non-Interactive Environments
299
300`prompt()` requires that it is run in an interactive environment. (I.e. [One where `process.stdin.isTTY` is `true`](https://nodejs.org/docs/latest-v12.x/api/process.html#process_a_note_on_process_i_o)). If `prompt()` is invoked outside of such an environment, then `prompt()` will return a rejected promise with an error. For convenience, the error will have a `isTtyError` property to programmatically indicate the cause.
301
302## User Interfaces and layouts
303
304Along with the prompts, Inquirer offers some basic text UI.
305
306#### Bottom Bar - `inquirer.ui.BottomBar`
307
308This UI present a fixed text at the bottom of a free text zone. This is useful to keep a message to the bottom of the screen while outputting command outputs on the higher section.
309
310```javascript
311var ui = new inquirer.ui.BottomBar();
312
313// pipe a Stream to the log zone
314outputStream.pipe(ui.log);
315
316// Or simply write output
317ui.log.write('something just happened.');
318ui.log.write('Almost over, standby!');
319
320// During processing, update the bottom bar content to display a loader
321// or output a progress bar, etc
322ui.updateBottomBar('new bottom bar content');
323```
324
325<a name="reactive"></a>
326
327## Reactive interface
328
329Internally, Inquirer uses the [JS reactive extension](https://github.com/ReactiveX/rxjs) to handle events and async flows.
330
331This mean you can take advantage of this feature to provide more advanced flows. For example, you can dynamically add questions to be asked:
332
333```js
334var prompts = new Rx.Subject();
335inquirer.prompt(prompts);
336
337// At some point in the future, push new questions
338prompts.next({
339 /* question... */
340});
341prompts.next({
342 /* question... */
343});
344
345// When you're done
346prompts.complete();
347```
348
349And using the return value `process` property, you can access more fine grained callbacks:
350
351```js
352inquirer.prompt(prompts).ui.process.subscribe(onEachAnswer, onError, onComplete);
353```
354
355## Support (OS Terminals)
356
357<a name="support"></a>
358
359You should expect mostly good support for the CLI below. This does not mean we won't
360look at issues found on other command line - feel free to report any!
361
362- **Mac OS**:
363 - Terminal.app
364 - iTerm
365- **Windows ([Known issues](#issues))**:
366 - [ConEmu](https://conemu.github.io/)
367 - cmd.exe
368 - Powershell
369 - Cygwin
370- **Linux (Ubuntu, openSUSE, Arch Linux, etc)**:
371 - gnome-terminal (Terminal GNOME)
372 - konsole
373
374## Known issues
375
376<a name="issues"></a>
377
378Running Inquirer together with network streams in Windows platform inside some terminals can result in process hang.
379Workaround: run inside another terminal.
380Please refer to the https://github.com/nodejs/node/issues/21771
381
382Calling a node script that uses Inquirer from grunt-exec can cause the program to crash. To fix this, add to your grunt-exec config `stdio: 'inherit'`.
383Please refer to https://github.com/jharding/grunt-exec/issues/85
384
385## News on the march (Release notes)
386
387<a name="news"></a>
388
389Please refer to the [GitHub releases section for the changelog](https://github.com/SBoudrias/Inquirer.js/releases)
390
391## Contributing
392
393<a name="contributing"></a>
394
395**Unit test**
396Unit test are written in [Mocha](https://mochajs.org/). Please add a unit test for every new feature or bug fix. `npm test` to run the test suite.
397
398**Documentation**
399Add documentation for every API change. Feel free to send typo fixes and better docs!
400
401We're looking to offer good support for multiple prompts and environments. If you want to
402help, we'd like to keep a list of testers for each terminal/OS so we can contact you and
403get feedback before release. Let us know if you want to be added to the list (just tweet
404to [@vaxilart](https://twitter.com/Vaxilart)) or just add your name to [the wiki](https://github.com/SBoudrias/Inquirer.js/wiki/Testers)
405
406## License
407
408<a name="license"></a>
409
410Copyright (c) 2022 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))
411Licensed under the MIT license.
412
413## Plugins
414
415<a name="plugins"></a>
416
417### Prompts
418
419[**autocomplete**](https://github.com/mokkabonna/inquirer-autocomplete-prompt)<br>
420Presents a list of options as the user types, compatible with other packages such as fuzzy (for search)<br>
421<br>
422![autocomplete prompt](https://github.com/mokkabonna/inquirer-autocomplete-prompt/raw/master/inquirer.gif)
423
424[**checkbox-plus**](https://github.com/faressoft/inquirer-checkbox-plus-prompt)<br>
425Checkbox list with autocomplete and other additions<br>
426<br>
427![checkbox-plus](https://github.com/faressoft/inquirer-checkbox-plus-prompt/raw/master/demo.gif)
428
429[**inquirer-date-prompt**](https://github.com/haversnail/inquirer-date-prompt)<br>
430Customizable date/time selector with localization support<br>
431<br>
432![Date Prompt](https://github.com/haversnail/inquirer-date-prompt/raw/master/examples/demo.gif)
433
434[**datetime**](https://github.com/DerekTBrown/inquirer-datepicker-prompt)<br>
435Customizable date/time selector using both number pad and arrow keys<br>
436<br>
437![Datetime Prompt](https://github.com/DerekTBrown/inquirer-datepicker-prompt/raw/master/example/datetime-prompt.png)
438
439[**inquirer-select-line**](https://github.com/adam-golab/inquirer-select-line)<br>
440Prompt for selecting index in array where add new element<br>
441<br>
442![inquirer-select-line gif](https://media.giphy.com/media/xUA7b1MxpngddUvdHW/giphy.gif)
443
444[**command**](https://github.com/sullof/inquirer-command-prompt)<br>
445Simple prompt with command history and dynamic autocomplete<br>
446
447[**inquirer-fuzzy-path**](https://github.com/adelsz/inquirer-fuzzy-path)<br>
448Prompt for fuzzy file/directory selection.<br>
449<br>
450![inquirer-fuzzy-path](https://raw.githubusercontent.com/adelsz/inquirer-fuzzy-path/master/recording.gif)
451
452[**inquirer-emoji**](https://github.com/tannerntannern/inquirer-emoji)<br>
453Prompt for inputting emojis.<br>
454<br>
455![inquirer-emoji](https://github.com/tannerntannern/inquirer-emoji/raw/master/demo.gif)
456
457[**inquirer-chalk-pipe**](https://github.com/LitoMore/inquirer-chalk-pipe)<br>
458Prompt for input chalk-pipe style strings<br>
459<br>
460![inquirer-chalk-pipe](https://github.com/LitoMore/inquirer-chalk-pipe/raw/master/screenshot.gif)
461
462[**inquirer-search-checkbox**](https://github.com/clinyong/inquirer-search-checkbox)<br>
463Searchable Inquirer checkbox<br>
464
465[**inquirer-search-list**](https://github.com/robin-rpr/inquirer-search-list)<br>
466Searchable Inquirer list<br>
467<br>
468![inquirer-search-list](https://github.com/robin-rpr/inquirer-search-list/blob/master/preview.gif)
469
470[**inquirer-prompt-suggest**](https://github.com/olistic/inquirer-prompt-suggest)<br>
471Inquirer prompt for your less creative users.<br>
472<br>
473![inquirer-prompt-suggest](https://user-images.githubusercontent.com/5600126/40391192-d4f3d6d0-5ded-11e8-932f-4b75b642c09e.gif)
474
475[**inquirer-s3**](https://github.com/HQarroum/inquirer-s3)<br>
476An S3 object selector for Inquirer.<br>
477<br>
478![inquirer-s3](https://github.com/HQarroum/inquirer-s3/raw/master/docs/inquirer-screenshot.png)
479
480[**inquirer-autosubmit-prompt**](https://github.com/yaodingyd/inquirer-autosubmit-prompt)<br>
481Auto submit based on your current input, saving one extra enter<br>
482
483[**inquirer-file-tree-selection-prompt**](https://github.com/anc95/inquirer-file-tree-selection)<br>
484Inquirer prompt for to select a file or directory in file tree<br>
485<br>
486![inquirer-file-tree-selection-prompt](https://github.com/anc95/inquirer-file-tree-selection/blob/master/example/screenshot.gif)
487
488[**inquirer-tree-prompt**](https://github.com/insightfuls/inquirer-tree-prompt)<br>
489Inquirer prompt to select from a tree<br>
490<br>
491![inquirer-tree-prompt](https://github.com/insightfuls/inquirer-tree-prompt/blob/main/example/screenshot.gif)
492
493[**inquirer-table-prompt**](https://github.com/eduardoboucas/inquirer-table-prompt)<br>
494A table-like prompt for Inquirer.<br>
495<br>
496![inquirer-table-prompt](https://raw.githubusercontent.com/eduardoboucas/inquirer-table-prompt/master/screen-capture.gif)
497
498[**inquirer-interrupted-prompt**](https://github.com/lnquy065/inquirer-interrupted-prompt)<br>
499Turning any existing inquirer and its plugin prompts into prompts that can be interrupted with a custom key.<br>
500<br>
501![inquirer-interrupted-prompt](https://raw.githubusercontent.com/lnquy065/inquirer-interrupted-prompt/master/example/demo-menu.gif)
502
503[**inquirer-press-to-continue**](https://github.com/leonzalion/inquirer-press-to-continue)<br>
504A "press any key to continue" prompt for Inquirer.js<br>
505<br>
506![inquirer-press-to-continue](https://raw.githubusercontent.com/leonzalion/inquirer-press-to-continue/main/assets/demo.gif)
507