I wrote this because I needed it for a project and I did not think it was worth it to install some npm package just for this. The comment should explain most things you will need but ask me if you don’t understand something. Note that this code is not well tested (yet!) since I just wrote it this morning so post a comment when you find a bug.
- Short and long options (i.e. ‘
- Option parameters (i.e. ‘
- Mandatory options.
- Implicit help option.
- Option callback functions.
- Cumulated short options (i.e. ‘
- Repeatable options (i.e. ‘
--add value1 --add value2‘).
- Non-option arguments.
Notes (extracted from the comments):
- Parser is case-sensitive.
- The ‘-h|–help’ option is provided implicitly.
- Successfully parsed options will be available as fields in the “options” object.
- Non-option arguments found will be available in order in the “arguments” array.
- Options and their parameters must be separated by space.
- Either one of «short» or «long» must always be provided.
- The «callback» function is optional and is invoked each time the option is encountered.
- Cumulated short options are supported (i.e. ‘
- If an error occurs, the process is halted and the help message is shown.
- Options with the “multiple” attribute will be cumulated into arrays (even if found only once).
- The parser does *not* test for duplicate definitions in the schema array.
See the code for everything else you need to use it (i.e. a sample schema definition). I will not waste any more time talking about it; if you like it, paste it at the top of your NodeJS script and start playing with it, e.g.:
$ node options.js -tf /some/file.txt foo bar
Also, please tell me about any improvements or fixes you produce. Thanks and… enjoy!