Skip to content

Instantly share code, notes, and snippets.

@davidnormo
Created June 24, 2017 01:27
Show Gist options
  • Save davidnormo/540562ba0ba4647b2bfd3bf9263247e4 to your computer and use it in GitHub Desktop.
Save davidnormo/540562ba0ba4647b2bfd3bf9263247e4 to your computer and use it in GitHub Desktop.
json config file to cmd opts string
#!/usr/local/bin/node
const fs = require('fs');
const configPath = process.argv[2];
fs.readFile(configPath, (err, data) => {
if (err) {
console.error(err);
process.exit(1);
return;
}
console.log(jsonToCmdOpts(data.toString()));
});
/**
* Converts JSON objects into cmd option strings.
* If an object property is 1 character it is assumed to be the short
* opt syntax e.g. { "a": true, "all": true } ===> -a --all
*
* @param json {String}
* @return {String}
*/
function jsonToCmdOpts(json) {
let obj = JSON.parse(json);
let opts = '';
for (let prop in obj) {
if (obj[prop] === false) continue;
let delim = '=';
if (prop.length === 1) opts += `-${prop}`;
if (prop.length > 1) opts += `--${camelToKebab(prop)}`;
if (prop.length === 0) delim = '';
opts += typeof obj[prop] === 'boolean' ? ' ' : `${delim}${obj[prop]} `
}
return opts;
}
/**
* Converts a string from camel case to kebab case
* e.g. helloWorld ===> hello-world
*
* @param str {String}
* @return {String}
*/
function camelToKebab(str) {
return str.replace(/(?!^)([A-Z])/g, (m, p1) => '-'+p1.toLowerCase());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment