After reading this guide you will know how to:
To gather input from the user we are going to use asking package, because it’s simple and is not bloated with unneeded features. It is inspired by highly popular highline ruby gem. Let’s go ahead and install it:
1 | $ npm install asking --save |
Asking package exposes only 2 functions: ask and choose. Simple as that. ask method is for entering data manually and choose method is for selecting one of the possible answers. To get started with asking:
1 2 | var choose = require('asking').choose; var ask = require('asking').ask; |
To ask user a question:
1 2 3 | ask('What is your favourite color?', function (err, color) { // color variable contains the answer }); |
ask also supports default values and input validation:
1 2 3 4 5 6 7 | ask('What is your favourite color?', { default: 'green' }, function (err, color) { // color defaults to "green" }); ask('What is your favourite color?', { pattern: /red|green|blue/ }, function (err, color) { // color can be either "red", "green" or "blue" }); |
Password prompt is a bit different from the others, because it’s input should be hidden. To achieve this behavior with asking, simply:
1 2 3 | ask('Enter your password: ', { hidden: true }, function (err, password) { // password will be hidden in console }); |
Thanks to choose method, we can provide user with a list of possible answers to our question. For example:
1 2 3 4 | choose('Select a color: ', ['red', 'green', 'blue'], function (err, color, index) { // color is either "red", "green", "blue" // index is an index of answer }); |
which will output this in console:
For more information on asking, visit its Github repository.