UNPKG

2.42 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
7
8
9function parseData(arr, page, rank, file) {
10 if (!arr.length) {
11 const files = [];
12 files[rank] = file;
13 arr.push({
14 'page': page,
15 'files': files
16 })
17 return;
18 }
19
20 arr.every(item => {
21 if (item.page == page) {
22 item.files[rank] = file;
23 return false;
24 }
25 return true;
26 });
27}
28
29function writeFiles(data) {
30 const dist = __dirname + '/tmp';
31
32 if (fs.existsSync(dist)) fs.rmdirSync(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