UNPKG

2.41 kBJavaScriptView Raw
1const fs = require('fs');
2const path = require('path');
3const walk = require('walk');
4const yamlFront = require('yaml-front-matter');
5const sh = require('child_process').execSync;
6
7const dist = __dirname + '/tmp';
8
9
10function parseData(arr, page, rank, file) {
11 if (!arr.length) {
12 const files = [];
13 files[rank] = file;
14 arr.push({
15 'page': page,
16 'files': files
17 })
18 return;
19 }
20
21 arr.every(item => {
22 if (item.page == page) {
23 item.files[rank] = file;
24 return false;
25 }
26 return true;
27 });
28}
29
30function writeFiles(data) {
31
32 if (fs.existsSync(dist)) sh(`rm -rf ${dist}`);
33 fs.mkdirSync(dist);
34
35 for(var k in data) {
36 const category = data[k];
37 category.forEach(item => {
38 let outFile = '';
39 item.files.forEach(f => {
40 outFile += `require('${f}'),\n`
41 })
42
43 let out = `module.exports = [\n${outFile}]`
44
45 fs.writeFileSync(dist + `/__${item.page}.js`, out);
46 });
47 }
48
49
50}
51
52
53module.exports = function walkMD(config, callback) {
54 const mdData = {};
55
56 const walker = walk.walk(config.root);
57 walker.on('file', function (root, fileStats, next) {
58 const name = fileStats.name;
59 const ext = path.extname(name);
60 const basename = path.basename(name, config.ext);
61
62 const file = path.resolve('', root + '/' + name);
63 // console.log(file);
64 if (ext === config.ext) {
65 const input = fs.readFileSync(file, 'utf-8');
66 const yaml = yamlFront.loadFront(input, 'content');
67 // console.log(yaml);
68 const page = yaml.page;
69 const rank = yaml.rank;
70 const category = yaml.category;
71
72 if (!mdData[category]) mdData[category] = [];
73 parseData(mdData[category], page, rank, file);
74 // if (!mdData[title]) mdData[title] = {};
75 // if (!mdData[title].files) mdData[title].files = [];
76 // mdData[title].files[rank] = file;
77 }
78
79 next();
80 });
81
82
83 walker.on('end', () => {
84 console.log(mdData);
85 writeFiles(mdData);
86 fs.writeFileSync(__dirname + '/web/__md__.json', JSON.stringify(mdData));
87 if (callback) callback(mdData);
88 });
89
90 walker.on('error', (e) => {
91 console.log(e);
92 });
93}
\No newline at end of file