UNPKG

2.11 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 fs.writeFileSync(__dirname + '/tmp/__md__.json', JSON.stringify(mdData));
35 });
36}
37
38
39module.exports = function walkMD(config, callback) {
40 const mdData = {};
41
42 const walker = walk.walk(config.root);
43 walker.on('file', function (root, fileStats, next) {
44 const name = fileStats.name;
45 const ext = path.extname(name);
46 const basename = path.basename(name, config.ext);
47
48 const file = path.resolve('', root + '/' + name);
49 // console.log(file);
50 if (ext === config.ext) {
51 const input = fs.readFileSync(file, 'utf-8');
52 const yaml = yamlFront.loadFront(input, 'content');
53 // console.log(yaml);
54 const page = yaml.page;
55 const rank = yaml.rank;
56 const category = yaml.category;
57
58 if (!mdData[category]) mdData[category] = [];
59 parseData(mdData[category], page, rank, file);
60 // if (!mdData[title]) mdData[title] = {};
61 // if (!mdData[title].files) mdData[title].files = [];
62 // mdData[title].files[rank] = file;
63 }
64
65 next();
66 });
67
68
69 walker.on('end', () => {
70 console.log(mdData);
71 writeFiles(mdData);
72 fs.writeFileSync(__dirname + '/web/__md__.json', JSON.stringify(mdData));
73 if (callback) callback(mdData);
74 });
75
76 walker.on('error', (e) => {
77 console.log(e);
78 });
79}
\No newline at end of file