A lightweight module to help build a git-like command interface for your app.
Its job is to extract the command (the first argument, unless it's an option), check it's valid and either return it or throw. From there, you can parse the remaining args using your preferred option parser (e.g. command-line-args, minimist etc.).
Create a list of valid commands (
null represents "no command"). Supply it to
commandLineCommands(), receiving back an object with two properties:
command (the supplied command) and
argv (the remainder of the command line args):
const commandLineCommands =const validCommands = null 'clean' 'update' 'install'const command argv =/* print the command and remaining command-line args */consoleconsole
We'll assume the above script is installed as
example. Since the
validCommands list includes
null, running it without a command is valid:
$ example command: null argv: 
example with no command and one option:
$ example --verbose command: null argv: ["--verbose"]
example with both a command and an option:
$ example install --save something command: install argv: ["--save","something"]
example without a valid command will cause
commandLineCommands() to throw.
From here, you can make a decision how to proceed based on the
argv received. For example, if no command (
null) was passed, you could parse the remaining
argv for general options (in this case using command-line-args):
if command === nullconst commandLineArgs =const optionDefinitions =name: 'version' type: Boolean// pass in the `argv` returned by `commandLineCommands()`const options =if optionsversionconsole
The same example, using minimist:
if command === nullconst minimist =// pass in the `argv` returned by `commandLineCommands()``const options =if optionsversionconsole
Both examples use command-line-args for option-parsing.
- Simple: A basic app with a couple of commands.
- Advanced: A more complete example, implementing part of the git command interface.
const commandLineCommands =
commandLineCommands(commands, [argv]) ⇒
argv value supplied (or
process.argv by default), extracting and returning the
command and remainder of
argv. The command will be the first value in the
argv array unless it is an option (e.g.
Kind: Exported function
INVALID_COMMAND- user supplied a command not specified in
||One or more command strings, one of which the user must supply. Include
||An argv array, defaults to the global