Install prompts
masterInstall the prompts package via npm. This package supports Node 14 and above.
$ npm install --save promptsrepository·master·Indexed 27 days ago
https://github.com/terkelg/promptsA lightweight, promise-based Node.js library for creating interactive CLI prompts. Version 2.4.2 supports Node 14 and above. It features a variety of prompt types including text, password, number, confirm, list, toggle, select, multiselect, autocomplete, and date. The library supports dynamic prompt chains, input validation, formatting, and programmatic response injection via inject() and override() methods.
Install the prompts package via npm. This package supports Node 14 and above.
$ npm install --save promptsImport prompts and call the main function with a prompt object or an array of prompt objects. The function returns a Promise that resolves to an object containing the user's responses, keyed by the name property of each prompt.
const prompts = require('prompts');
(async () => {
const response = await prompts({
type: 'number',
name: 'age',
message: 'How old are you?',
validate: value => value < 18 ? `Nightclub is 18+ only` : true
});
console.log(response); // => { age: 24 }
})();Prompt properties like type can be functions. If a type function returns a falsy value, the prompt is skipped. This allows for conditional logic based on previous answers.
const prompts = require('prompts');
const questions = [
{
type: 'text',
name: 'dish',
message: 'Do you like pizza?'
},
{
type: prev => prev == 'pizza' ? 'text' : null,
name: 'topping',
message: 'Name a topping'
}
];
(async () => {
const response = await prompts(questions);
})();Pass an array of prompt objects to prompts() to execute a sequence of questions. Ensure each prompt has a unique name to avoid overwriting values in the resulting response object.
const prompts = require('prompts');
const questions = [
{
type: 'text',
name: 'username',
message: 'What is your GitHub username?'
},
{
type: 'number',
name: 'age',
message: 'How old are you?'
},
{
type: 'text',
name: 'about',
message: 'Tell something about yourself',
initial: 'Why should I?'
}
];
(async () => {
const response = await prompts(questions);
// => response => { username, age, about }
})();Use prompts.override(values) to automatically fill in answers. This is useful for integrating with command-line argument parsers like yargs.
const prompts = require('prompts');
prompts.override(require('yargs').argv);
(async () => {
const response = await prompts([
{
type: 'text',
name: 'twitter',
message: `What's your twitter handle?`
}
]);
})();Use prompts.inject(values) to prepare responses ahead of time, primarily for testing. If an injected value is an Error, it simulates a user cancellation/exit.
const prompts = require('prompts');
// Injecting a single value and an array of values for multiple questions
prompts.inject([ '@terkelg', ['#ff0000', '#0000ff'] ]);
(async () => {
const response = await prompts([
{
type: 'text',
name: 'twitter',
message: `What's your twitter handle?`
},
{
type: 'multiselect',
name: 'color',
message: 'Pick colors',
choices: [
{ title: 'Red', value: '#ff0000' },
{ title: 'Green', value: '#0000ff' },
{ title: 'Blue', value: '#0000ff' }
],
}
]);
// => { twitter: 'terkelg', color: [ '#ff0000', '#0000ff' ] }
})();The prompts(prompts, options) function accepts an options object with two lifecycle callbacks:
onSubmit(prompt, answer, answers): Invoked after each submission. Returning true quits the chain and returns collected responses. Async supported.onCancel(prompt, answers): Invoked when the user cancels. Returning true prevents the loop from aborting and continues prompting.// onSubmit example
const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`);
const response = await prompts(questions, { onSubmit });
// onCancel example
const onCancel = prompt => {
console.log('Never stop prompting!');
return true;
}
const response = await prompts(questions, { onCancel });A prompt object defines the question. Most properties can be functions with the signature (prev, values, prompt), where prev is the previous answer, values is the full response object, and prompt is the previous prompt object.
Key properties:
type: String | Function. If falsy, the prompt is skipped.name: String | Function. The key in the response object.message: String | Function. The text displayed to the user.initial: String | Function | Async Function. Default value.format: Function. Transforms the input before adding it to the response. Signature: (val, values).onRender: Function. Callback when rendering. Receives kleur as the first argument.onState: Function. Callback on state change. Receives state object { value, aborted }.stdin / stdout: Stream. Custom input/output streams (defaults to process.stdin/process.stdout).{
type: 'number',
name: 'price',
message: 'Enter price',
format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val);
}The override(answers) function allows you to force specific answers for questions based on their name. This takes precedence over user input and injected values.
answers must be an object where keys match the name property of the question objects.format and validate logic is still applied to the overridden value.prompts package provides several specialized prompt elements for different types of user input. You can import these elements to build interactive CLI interfaces. Available prompt types include text, selection, toggles, dates, numbers, multiselect, autocomplete, and confirmation prompts.The prompt() function handles a single question object or an array of question objects. It iterates through the questions, manages user input via specific prompt types, and returns an object containing the collected answers.
Key features:
type is a function, it is evaluated with the current answer, answers (all previous answers), and the question object to determine the prompt type.passOn list (suggest, format, onState, validate, onRender, type) can be a function. These functions are invoked with (answer, answers, lastPrompt) to allow dynamic configuration.validate function is provided, it must return true for the answer to be accepted.format function can be used to transform the answer before it is stored.onSubmit(question, answer, answers) and onCancel(question, answers) callbacks.onSubmit returns a truthy value, the prompting process stops and returns the current answers.lib/dateparts module exports several prompt components used to capture specific parts of a date or time. These components can be used within a prompt chain or as individual prompts to ensure structured date/time input.