A question object is a hash containing configuration for a specific prompt. Key properties include:
- type (String): The prompt type. Defaults to
input. Possible values: input, number, confirm, list, rawlist, expand, checkbox, password, editor. - name (String): The key used to store the answer in the results object. Periods in the name define a path in the answers hash.
- message (String|Function): The question text. If a function, the first parameter is the current answers hash.
- default (String|Number|Boolean|Array|Function): The default value. If a function, the first parameter is the current answers hash.
- choices (Array|Function): An array of choices or a function returning them. Array values can be simple types or objects with
{ name, value, short }. - validate (Function): Validates input. Returns
true if valid, or a String error message if invalid. - filter (Function): Transforms the input before it is added to the answers hash.
- transformer (Function): Transforms the input for display purposes only (does not affect the stored answer).
- when (Function|Boolean): Determines if the question should be asked based on previous answers.
- pageSize (Number): Limits the number of lines rendered for list-based prompts.
- prefix / suffix (String): Customizes the prompt decoration.
- askAnswered (Boolean): If true, forces the prompt even if the answer is already in the
answers object. - loop (Boolean): Enables list looping. Defaults to
true. - waitUserInput (Boolean): Whether to wait for input before opening the system editor. Defaults to
true.
Note on Asynchronicity: default, choices, validate, filter, and when can be asynchronous. You can return a Promise or use the legacy this.async() method.
{
/* 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
const 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');
} else {
done(null, true);
}
}, 3000);
}
}