So this week I have been looking into option parsers, for the sake of expanding my horizons when it comes to what the options are for parsing options. I have writing a post on nopt a long time ago, which was one of the first option parsers I have dealt with. It works fine, but so far I think I am liking commander the best. However this post is about another popular option parser for node.js called yargs.
When making on of my posts on an npm package I start out with simple examples, then I might progress into some more advanced stuff from there. When it comes to an option parser at a minimum I would want to know how to define one or more options, and then I would want to also know how to set some defaults for them as well.
For starters I made a basic.js file where I just log to the console the value of a single option that I have called basic. When options are parsed with yargs they will be a value of the argv object when bringing yargs into a project with require.
So when I call my basic.js file from the command line with node it works as expected. When I give the basic option the value is true, and if I give a no-basic option then it has a value of false.
However if I do not give any option then I get a value of undefined, however this can be resolved by setting some defaults.
So if I want to set some defaults for an option then that is just a matter of using the defaults method.
So when I just call my defaults.js file from the command line, and do not give any option at all, as expected the set default is assumed. I can then use the –no-basic option to set the basic option to false.
For a more interesting example I put together a quick script that can be used to walk a file system and log any html files that it finds.
In this example I am setting up a default command that will display a usage example when the script is called without a command given. I am also defining my commands by giving an object rather than three sets of arguments.
So the way I often like to use yargs in actual projects is to create a commands folder that will contains a whole bunch of scripts and each script is a command. So I will want to make it so each script exports an object that is formated the same way as the obejcts that I use to define what a command is.