UNPKG

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