Synopt: Sane Javascript Options Parsing

While working on another project written in NodeJS, I had to parse command line options. Confident that must be solved problem, I hopped over to NPM and looked at the two most popular options.

With the first I tried to get along for a while, but it was very hard to make it behave. In unit tests, it insisted on suddenly calling exit and stop the process. That's one of the few things that make automated testing impossible. Upon further research I came across what looked like promising the solution: a function called exitOverride. When trying to use it, I found it would still assume the process ending! Only I had to do it myself some other way - voluntarily. One of the maintainers of the package confirmed this to me as fact. So I turned to the next option.

When checking out the second most popular option, I found it had the expectation to take over control right from the get-go, and again calling exit in some circumstances. I didn't further investigate if I was able to accomodate with these.

I started thinking. How hard can it be to write an options parser? It sounds like 40 lines of code. That thought is usually dangerous, every experienced programmer knows that. But still, I started writing what I wanted to use. It turned out to be some more lines, and it took longer that I can really justify to myself. But now it's there, and I have decided to extract it from its surrounding application, and published it.

The ideas are really simple, and the focus is narrow.

  • declare options, with both long and short forms (-n, --name, etc.)
  • generate the usage banner from the declarations
  • parse the argument vector, and provide a clean options map (object)
  • easy, safe testing - never call exit
  • return parse errors in a controlled manner, no exceptions

The source is fully Typescript.

And that's it. Check it out if you are interested something like this.

Github
NPM