Last active
September 10, 2021 16:33
-
-
Save unisys12/93b40113552a9616b4dae8560d054bac to your computer and use it in GitHub Desktop.
Generate CSS Custom Properties from Periodic Table of Elements data using Nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fsPromise = require("fs/promises"); | |
const cssPath = "./assets/css/vars.css"; | |
readJson = async () => { | |
const path = "./assets/_data/periodic-table.json"; | |
try { | |
const data = fsPromise.readFile(path, "utf-8"); | |
data.then((fileData) => { | |
const jsonElements = JSON.parse(fileData); | |
compileCssVars(jsonElements); | |
compileIdProps(jsonElements); | |
}); | |
} catch (err) { | |
console.error(err); | |
} | |
}; | |
/** | |
* writes a css custom property to the vars.css file | |
* ex: | |
* :root { | |
* --H: FFFFFF; | |
* } | |
*/ | |
compileCssVars = async (data) => { | |
let css = []; | |
const cssStart = ":root {"; | |
const cssEnd = "}\n\n"; | |
css.push(cssStart); | |
data.forEach((element) => { | |
// Check for `${element.cpkHexColor}` == 'unknown'; | |
css.push(`--${element.symbol}: #${element.cpkHexColor};`); | |
}); | |
css.push(cssEnd); | |
writeCss(css.join("\n")); | |
}; | |
/** | |
* appends custom id calls to vars.css file where above properties are used | |
* ex: | |
* #He { | |
* background-color: var(--He); | |
* } | |
*/ | |
compileIdProps = async (data) => { | |
data.forEach((element) => { | |
appendVars( | |
`#${element.symbol} { | |
background-color: var(--${element.symbol}); | |
}\n\n` | |
); | |
}); | |
}; | |
writeCss = async (data) => { | |
try { | |
await fsPromise.writeFile(cssPath, data); | |
} catch (error) { | |
console.error(error); | |
} | |
}; | |
appendVars = async (data) => { | |
try { | |
await fsPromise.appendFile(cssPath, data); | |
} catch (error) { | |
console.log(error); | |
} | |
}; | |
readJson(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment