mirror of
https://github.com/flynx/argv.js.git
synced 2025-10-29 10:50:06 +00:00
3.0 KiB
3.0 KiB
argv.js
Simple argv parser
Motivation
I needed a new argv parser for a quick and dirty project I was working
on and evaluating and selecting the proper existing parser and then
learning its API, quirks and adapting the architecture to it seemed
to be more complicated, require more effort and far less fun than
putting together a trivial parser myself in a couple of hours.
This code is an evolution of that parser.
Features
- Simple
- Supports both the option (a-la
find) and command (a-lagit) paradigms - Nestable
parsers can be nested as option/command handlers defining independent nested contexts - Option expansion
-abcexpands to-a -b -cif-abcis not defined - Option/command value passing
implicit-a 123(requires definition or manual handling) or explicit-a=123 - Environment variable option/command values
env can control option defaults - Reasonable defaults
-help– generate and print help,-version– print version,-– stop argument processing,- common option aliases
- Extensible:
- Hooks for option value conversion (XXX should this be implemented???)
- Hooks for dynamic option/command handling
- Customizable error and stop condition handling
Installation
$ npm install ig-argv
Basic usage
Create a script and make it runnable
$ touch script.js
$ chmod +x script.js
Now for the code
#!/usr/bin/env node
// compatible with both node's and RequireJS' require(..)
var argv = require('ig-argv')
var parser = argv.Parser({
// basic/quick option...
'-b': '-basic',
'-basic': function(){
// ...
},
// full option settings...
'-f': '-full',
'-full': {
doc: 'Option help',
// option value to be displayed in help (optional)
arg: 'VALUE',
// value key (optional)
// NOTE: if .handler(..) is defined this is ignored.
key: 'fullValue',
// envioroment value (optional)
env: 'VALUE',
// default value (optional)
default: 123,
// required status (optional)
required: true,
// handler (optional)
handler: function(opts, key, value){
// ...
},
},
// command...
// NOTE: the only difference between an option and a command is
// the prefix ('-' vs. '@') that determines how it is parsed,
// otherwise they are identical and can alias each other...
'@cmd', '@command',
'@command': {
// ...
},
// example command-option alias...
'@help': '-help',
// nested parser...
'@nested': argv.Parser({
// ...
}).then(function(){
// ...
}),
})
.then(function(){
// XXX
})
// run the parser only if script.js is run directly...
if(__filename == require.main){
parser(process.argv) }
This will create a parser that supports the folowing:
$ ./script.js --help
Configuration
License
Copyright (c) 2016-2020, Alex A. Naanou,
All rights reserved.