Skip to content

Commit 6e84f7a

Browse files
committed
add json-to-file.js
1 parent 895d3ea commit 6e84f7a

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

test/json-to-files.js

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

0 commit comments

Comments
 (0)