When making scripts that are to be called from the command line with node.js, the subject of option parsing becomes of interest. Option parsing is the process of parsing a string of arguments from a command line interface into a workable object of values. If you are in a situation in which you find yourself trying to work out your own solution for extracting arguments that are given from the command line via process,argv, you might want to stop and check out some of the npm modules that are around that help to make quick work of this such as commander. In this post I will be writing about commander as a solution for command line option parsing, and will be giving some examples of it’s use.
I have writne a post on another one called nopt and I am sure there are many others. It would appear that commander is very popular, and it sure does get the job done well. I am not recommending nopt over commander, just pointing out that there are options, and that one of them should be used over bothering with this from the ground up in most cases.
For a basic example of commander I made a quick little example that will grab the version number from the package.json file, and use that as the version number that is to be displayed when the version argument is given.
I start by requiring in commander, which gives me an object that is used to define options, and commands for the program. I finish by parsing and given arguments from the command line that are in process.argv
Setting options for the program just involves using the option method that can be chained. I can give both long, and short options, and there are a few conventions to look out for about this.
If I just want to have a simple true or false style option then I just need to give the string of option names, and a description like this.
With commander a command is when I want to make some kind of command for a command. For example with the static website generator hexo that I use to build this site I do this in the command line when in a hexo project folder:
however if I do not what to build my site, but just serve it up locally I can do this:
When doing that the public folder will be hosted locally, and I can view what I have so far before actually publishing. When making a command in commander this allows me to define these kinds of sub commands for commands.
When defining the string that will be the command it is possible to set one or more arguments that should be given after it, such as a directory or some numbers. These additional arguments can be optional or required.
So for an example of this I made a command that will give me the x, and y position of a pint that lays a given angle, and distance relative to a starting position. The starting position defaults to 0,0 but I can set it with additional options, I also have an additional option that will display more info if given.
Some use examples calling it with node.