forked from 4GeeksAcademy/4GeeksAcademy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-json.js
93 lines (78 loc) Β· 2.42 KB
/
generate-json.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const fs = require('fs');
const path = require('path');
const jsyaml = require("js-yaml");
// const fm = require('front-matter');
// open a directory and find all the files inside (recursively)
const walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
results.push(file);
if (!--pending) done(null, results);
}
});
});
});
};
const buildResumesData = (resumes) => resumes
.map(resumeYmlContent => {
const { fileName, yaml } = loadYML(resumeYmlContent);
return {
...yaml
};
});
const createContentJSON =(content, fileName) => {
const outputPath = "site/static/"
if (!fs.existsSync(outputPath)) fs.mkdirSync(outputPath);
else console.error("Output path does not exist, creating it: ", outputPath)
fs.writeFileSync(outputPath+fileName+".json", JSON.stringify(content));
};
walk('site/resumes/', function(err, results) {
if (err){
console.log("Error scanning resume (yml) files");
process.exit(1);
}
try{
// "bildResumeData" will open the resume yml and convert it to an object
const resumes = buildResumesData(results);
// console.log(resumes)
createContentJSON(resumes, "resumes");
// console.log("The /public/static/api/lessons.json file was created!");
process.exit(0);
}
catch(error){
console.log(error);
process.exit(1);
}
});
const loadYML = (pathToFile) => {
const content = fs.readFileSync(pathToFile, "utf8");
try {
const yaml = jsyaml.load(content);
// get the file name from the path
const fileName = pathToFile
.replace(/^.*[\\\/]/, "")
.split(".")
.slice(0, -1)
.join(".")
.toLowerCase();
//if the yml parsing succeeded
if (typeof yaml == "undefined" || !yaml)
throw new Error(`The file ${fileName}.yml was impossible to parse`.red);
return { fileName, yaml };
} catch (error) {
console.error(error);
return null;
}
};