Skip to content

Instantly share code, notes, and snippets.

@gadflying
Last active January 8, 2021 21:38
Show Gist options
  • Select an option

  • Save gadflying/73c576da6a1a975e76aa5bc6da8598fb to your computer and use it in GitHub Desktop.

Select an option

Save gadflying/73c576da6a1a975e76aa5bc6da8598fb to your computer and use it in GitHub Desktop.
[How to parse command line arguments] #nodejs #yargs

Passing in arguments via the command line

all command-line arguments received by the shell are given to the process in an array called argv

console.log(process.argv);

Now save it, and try the following in your shell:

$ node argv.js one two three four five
[ 'node',//node
  '/home/avian/argvdemo/argv.js',//the path to your script
  'one',
  'two',
  'three',
  'four',
  'five' ]

Where everyday CLI arguments are concerned, you'll want to skip the first two. Now try this in argv.js:

var myArgs = process.argv.slice(2);
console.log('myArgs: ', myArgs);

This yields:

$ node argv.js one two three four five
myArgs:  [ 'one', 'two', 'three', 'four', 'five' ]

Now let's actually do something with the args:

var myArgs = process.argv.slice(2);
console.log('myArgs: ', myArgs);

switch (myArgs[0]) {
case 'insult':
    console.log(myArgs[1], 'smells quite badly.');
    break;
case 'compliment':
    console.log(myArgs[1], 'is really cool.');
    break;
default:
    console.log('Sorry, that is not something I know how to do.');
}

Referring to your command-line arguments by array index isn't very clean, and can quickly turn into a nightmare when you start working with flags and the like - imagine you made a server, and it needed a lot of arguments. Imagine having to deal with something like myapp -h host -p port -r -v -b --quiet -x -o outfile - some flags need to know about what comes next, some don't, and most CLIs let users specify arguments in any order they want. Sound like a fun string to parse?

yargs.

npm i yargs
const yargs = require('yargs');

const argv = yargs
    .command('lyr', 'Tells whether an year is leap year or not', {
        year: {
            description: 'the year to check for',
            alias: 'y',
            type: 'number',
        }
    })
    .option('time', {
        alias: 't',
        description: 'Tell the present Time',
        type: 'boolean',
    })
    .help()
    .alias('help', 'h')
    .argv;

if (argv.time) {
    console.log('The current time is: ', new Date().toLocaleTimeString());
}

if (argv._.includes('lyr')) {//argv._
    const year = argv.year || new Date().getFullYear();
    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
        console.log(`${year} is a Leap Year`);
    } else {
        console.log(`${year} is NOT a Leap Year`);
    }
}

console.log(argv);

The last line was included to let you see how yargs handles your arguments.

argv.$0 contains the name of the script file which is executed like: '$0': 'myapp.js'. argv._ is an array containing each element not attached to an option(or flag) these elements are referred as commands in yargs. Individual options(flags) become properties of argv, such as with argv.h and argv.time. Note that non-single-letter flags must be passed in as --flag like: node myapp.js --time. A summary of elements used in the program:

argv: This is the modified process.argv which we have configured with yargs. command(): This method is used to add commands, their description and options which are specific to these commands only, like in the above code lyr is the command and -y is lyr specific option: node myapp.js lyr -y 2016 option(): This method is used to add global options(flags) which can be accessed by all commands or without any command. help(): This method is used to display a help dialogue when --help option is encountered which contains description of all the commands and options available. alias(): This method provides an alias name to an option, like in the above code both --help and -h triggers the help dialogue.

Basic usage

var argv = require('yargs').argv;

argv._         // [ ... ]
argv.$0        // "node bin/mybin"
argv.verbose   // --verbose
import { argv } from 'yargs';
const programIDArguments = argv._;
[
  "nj-dp3-spinnaker-1.0"
]

Help and version

var argv = require('yargs')

  // version
  .alias('v', 'version')
  .version(function() { return require('../package').version; })
  .describe('v', 'show version information')

  // help text
  .alias('h', 'help')
  .help('help')
  .usage('Usage: $0 -x [num]')
  .showHelpOnFail(false, "Specify --help for available options")

Options

  .option('f', {
      alias : 'file',
      describe: 'x marks the spot',
      type: 'string', /* array | boolean | string */
      nargs: 1,
      demand: true,
      demand: 'file is required',
      default: '/etc/passwd'
      // also: count:true, requiresArg:true
  })

  .options({
    f: { ... }
  })
    

Examples and more help stuff

  // more help
  .example('...')
  .epilog('copyright 2015')
  .command('start', 'start a server')

Stacking

  .count('verbose')
argv.verbose // -vvv => 3

Reject non explicits

  .strict()

Methods

yargs.showHelp()
yargs.help() //=>string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment