:arrow_forward: :red_circle: cli-select
Simple and interactive solution to provide a list of selectable items on the command line.
Note: cli-select does not produce colored output by default to keep the dependencies at a minimum. See the examples below on how to reproduce this preview.
Table of contents
Installation
npm install --save cli-select
Usage
const cliSelect = require('cli-select');
cliSelect(options, callback);
See the configuration section for all available options.
The select list gets immediately rendered when the function gets called and the user can then select an option with the up
and down
arrow keys. To confirm the selection, just press enter
/return
. It is also possible to cancel a selection with ctrl+c
or esc
but it is up to you how you want to handle the cancellation of a selection, the process won't be ended by default.
cli-select supports both, a callback function or a Promise (if your node environment supports promises).
Callback
If the callback function is defined, two parameters will get passed where valueId
is the numeric index if values is an array or the object key if values is an object. Both parameters will be null
if the selection gets cancelled.
cliSelect(options, (valueId, value) => {
if (valueId !== null) {
console.log('selected ' + valueId + ': ' + value);
} else {
console.log('cancelled');
}
});
Promise
If no callback function is defined, a Promise will be returned:
cliSelect(options).then((response) => {
console.log('selected ' + response.id + ': ' + response.value);
}).catch(() => {
console.log('cancelled');
});
Configuration
Note: All options are optional except values
and will default as specified below.
The configuration gets passed to the cliSelect
function as a normal object and can contain the following keys:
cliSelect({
values: [],
defaultValue: 0,
selected: '(x)',
unselected: '( )',
indentation: 0,
cleanup: true,
valueRenderer: (value, selected) => value,
outputStream: process.stdout,
inputStream: process.stdin,
});
Examples
cli-select
does not produce colored outputs by default so you can use the package for that which you already have in your project and you don't have two packages doing basically the same at the end.
If you don't have such a package already in your project and you want the output to look similar to the preview gif above,
I recommend the packages chalk for colored output and
figures for unicode symbols with fallbacks.
These two packages are also used in the examples below but cli-select
is also compatible with every other package.
Custom value renderer
const cliSelect = require('cli-select');
const chalk = require('chalk');
cliSelect({
values: ['Major', 'Minor', 'Patch'],
valueRenderer: (value, selected) => {
if (selected) {
return chalk.underline(value);
}
return value;
},
}).then(...);
Todo: more examples, also the one in the preview gif
License
MIT