Command-line Configuration with confab and yargs
- 3/2/2016
confab
is a great tool for configuring node.js applications, but it
doesn’t ship with support for command-line flags. CLIs can vary quite a bit from
one application to the next, and confab
does not make assumptions (or force
opinions) about their design.
Fortunately, there are plenty of other argument-processing tools that can be
easily integrated with confab
. One such is yargs
, which (in
addition to a pirate motif and a laundry list of other useful features) exposes
command-line arguments as the yargs.argv
object:
var argv = require('yargs').argv;
console.log(argv.foo);
$ node index.js --foo=baz
'baz'
Since argv
is just an object, integrating with confab requires an
almost-trivial use of the assign
transform:
var confab = require('confab');
var argv = require('yargs').argv;
var pick = require('lodash.pick');
var CONFIG_DEFAULTS = {
foo: 'bar'
};
var CONFIG_KEYS = Object.keys(CONFIG_DEFAULTS);
var config = confab([
confab.defaults(CONFIG_DEFAULTS),
confab.assign(pick(argv, CONFIG_KEYS)),
confab.required(CONFIG_KEYS)
]);
process.stdout.write(JSON.stringify(config, null, 2) + '\n');
process.exit(0);
No surprises here.
$ node index.js
{ foo: 'bar' }
$ node index.js --foo=baz
{ foo: 'baz' }
Just like that, we’ve bolstered our configuration with command-line overrides. CLI support is missing no longer–we just needed to set it up!