Lets get user inputs using inquirer and Yargs — Creating a npm command line Utility — Part 2
--
now lets see how we can get user inputs to over commandline uility
Description:
We have seen how to create a simple command line utility that prints “Hello User!”. Now we will see how we can accept user inputs and print the input instead of the hardcoded value
This is continuation of previous article
Lets get started:
YARGS
CJS setup:
First lets see how to do this in cjs (plain javascript)
Currently we have the below project structure from the previous article
Now we have to get user input for replacing the hardcoded name, this can be done by using yargs (non interactive) or inquirer (interactive) . You can directly use process.argv but it is not a clean way to do it as it wont sanitize the user inputs.
Yargs setup:
install yargs : npm install yargs --save
Now update the index.js file as :
#! /usr/bin/env node
const {print} = require('./src/printer'),
yargs = require('yargs')let OPTIONS = yargs
.usage('\nUsage: -n "yourname"')
.usage('\nor\n\nUsage: -i')
.strict()
.option('i', { alias: 'interactive', describe: 'Pass -i to enter Interactive mode', type: 'boolean', default: false })
.option('n', { alias: 'name', describe: 'Your name', type: 'string', demandOption: true})
.argvprint(OPTIONS.name);
here we are creating yargs to print usage instrutction, and telling only know options are allowed (strict()) . If user gives unknown options or commands it will be rejected . option method creates the options that we are expecting and the demandOption says this is a required option
Type script setup:
Install yargs : npm install yargs --save
install yargs types : npm install @types/yargs --save-dev