json-to-files.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const path = require('path');
  2. const fs = require('fs');
  3. const folder = process.argv[2];
  4. const jsonFile = process.argv[3];
  5. if (!folder || !jsonFile) {
  6. console.log('node ./json-to-files.js {path to folder} {path to json file}');
  7. process.exit(1);
  8. }
  9. const specs = require(jsonFile);
  10. const files = specs.reduce((obj, spec) => {
  11. if (!obj[spec.section]) {
  12. obj[spec.section] = {
  13. md: [],
  14. html: [],
  15. options: {}
  16. };
  17. }
  18. obj[spec.section].md.push(spec.markdown);
  19. obj[spec.section].html.push(spec.html);
  20. Object.assign(obj[spec.section].options, spec.options);
  21. return obj;
  22. }, {});
  23. try {
  24. fs.mkdirSync(folder, {recursive: true});
  25. } catch (ex) {
  26. // already exists
  27. }
  28. for (const section in files) {
  29. const file = files[section];
  30. const name = section.toLowerCase().replace(' ', '_');
  31. const frontMatter = Object.keys(file.options).map(opt => {
  32. let value = file.options[opt];
  33. if (typeof value !== 'string') {
  34. value = JSON.stringify(value);
  35. }
  36. return `${opt}: ${value}`;
  37. }).join('\n');
  38. let markdown = file.md.join('\n\n');
  39. if (frontMatter) {
  40. markdown = `---\n${frontMatter}\n---\n\n${markdown}`;
  41. }
  42. const html = file.html.join('\n\n');
  43. const mdFile = path.resolve(folder, `${name}.md`);
  44. const htmlFile = path.resolve(folder, `${name}.html`);
  45. if (fs.existsSync(mdFile) || fs.existsSync(htmlFile)) {
  46. throw new Error(`${name} already exists.`);
  47. }
  48. fs.writeFileSync(mdFile, markdown);
  49. fs.writeFileSync(htmlFile, html);
  50. }