A command-line argument helper that allows complex keys (JSON dot paths) and complex values (valid JSON).
npm install dot-argvnpm install dot-argv
Execute:
node app.js param0 --opt1 value1 -opt2 val=ue2 -opt3 \"value3\" -opt4.a.x [3,\"ok\",false] -opt5\\.z {\"b\":3} par\\=am1 {\"c\":3}
Where, in app.js:
var argv = require('dot-argv');
console.log(argv.opts);
console.log(argv.params);
Which gives argv.opts as:
{
"opt1": "value1",
"opt2": "val=ue2",
"opt3": "value3",
"opt4": {
"a": {
"x": [ 3, "ok", false ]
}
},
"opt5.z": {
"b": 3
}
}
And argv.params as:
[ "param0", "par=am1", { "c": 3 } ]
argv.opts from the usage example: argv.val(argv.opts, "opt4.a.x"); // returns [ 3, "ok", false ]
argv.val(argv.opts, "opt4.a.x", 1000); // writes the value
argv.val(argv.opts, "opt5\\.z.b"); // returns 3
argv.val(argv.opts, "opt5\\.z.b", 4); // writes the value
argv.opts from the usage example: argv.collapse(argv.opts);
Returns:
{
"opt1": "value1",
"opt2": "val=ue2",
"opt3": "value3",
"opt4.a.x.0": 3,
"opt4.a.x.1": "ok",
"opt4.a.x.2": false,
"opt5\\.z.b": 3
}
Recreate the structure with:
argv.expand(flat);
Which returns a copy of the original object, argv.opts.
Write properties in one object into another.
Useful if you have an object containing default values that need to be partially overwritten.
E.g. writing argv.opts into a defaults object:
var defaults = {
"opt1": "default value1",
"opt4": {
a: false;
},
"opt6": 1000
};
var opts = argv.overwrite(argv.opts, defaults);
Then opts is:
{
"opt1": "value1",
"opt2": "val=ue2",
"opt3": "value3",
"opt4": {
"a": {
"x": [ 3, "ok", false ]
}
},
"opt5.z": {
"b": 3
},
"opt6": 1000 // this property is preserved from defaults object
}
Create an array of command-line option strings. E.g. with the argv.opts in the usage example:
argv.arrayify(argv.opts);
Returns an array of the collapsed form, with JSON.stringify()'d values:
[
'"param0"',
'"par\\=am1"',
'{"c":3}',
'opt1', '"value1"',
'opt2', '"val=ue2"',
'opt3', '"value3"',
'opt4.a.x.0', '3',
'opt4.a.x.1', '"ok"',
'opt4.a.x.2', 'false',
'opt5\\.z.b', '3'
]
Order of the keyed options is not guaranteed.
Similar to arrayify, but returns a string. E.g. with the argv.opts in the usage example:
argv.arrayify(argv.opts);
Returns the string:
'"param0" "par\\=am1" {"c":3} --opt1 "value1" -opt2 "val=ue2" -opt3 "value3" -opt4.a.x.0 3 -opt4.a.x.1 "ok" -opt4.a.x.2 false -opt5\.z.b 3'