README.md

Node CLI Router

Version 0.3.0

I build a lot of Node CLI tools and one of the things I've always wanted is a small router for user arguments.

I build a lot of websites using Sinatra and I love how in Sinatra you can route URLs to functions easily. I decided to take a go at doing something similar for command line flags and arguments for CLI tools.

Multiple Routes

When $ foo -a 5 -b is run, the first route will be used, because it was defined first.

Joined up Arguments

The router is able to split arguments up, allowing your users to enter them joined. For example, with this match:

router.match("-a -b -c", function() {});

All of these will be matched:

$ foo -abc
$ foo -bca
$ foo -a -b -c

In fact, you can even used joined up arguments in your match calls:

router.match("-abc", function() {});

Which will match all of:

$ foo -abc
$ foo -b -a -c
$ foo -bca
$ foo -a -b -c
... and so on

Other Arguments

Some tools might take it one main argument and then allow flags to be set. For example:

$ foo test.txt -a -b -c

The CLI Router doesn't support this, but you can get around it yourself. Rather than calling router.go(process.argv), strip the user arguments out and call router.process on them. Using the above example, say the user passes in arguments such that process.argv looks like so:

["node", "/Users/MadeUp/yourscript.js", "test.txt", "-a", "-b"]

You can get the main argument, test.txt as process.argv[2], and then call router.process(process.argv.slice(3).join(" ")) to route based on the flags.

Contexts

If you care about the context in which the callback function is called, you can add it as a third parameter to match: