Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.