UNPKG

1.82 kBJavaScriptView Raw
1const fs = require('fs');
2const path = require('path');
3const walk = require('walk');
4const yamlFront = require('yaml-front-matter')
5
6
7function verifyExist(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
27
28module.exports = function walkMD(config, callback) {
29 const mdData = {};
30
31 const walker = walk.walk(config.root);
32 walker.on('file', function (root, fileStats, next) {
33 const name = fileStats.name;
34 const ext = path.extname(name);
35 const basename = path.basename(name, config.ext);
36
37 const file = path.resolve('', root + '/' + name);
38 // console.log(file);
39 if (ext === config.ext) {
40 const input = fs.readFileSync(file, 'utf-8');
41 const yaml = yamlFront.loadFront(input, 'content');
42 // console.log(yaml);
43 const page = yaml.page;
44 const rank = yaml.rank;
45 const category = yaml.category;
46
47 if (!mdData[category]) mdData[category] = [];
48 verifyExist(mdData[category], page, rank, file);
49
50
51
52
53 // if (!mdData[title]) mdData[title] = {};
54 // if (!mdData[title].files) mdData[title].files = [];
55 // mdData[title].files[rank] = file;
56 }
57
58 next();
59 });
60
61
62 walker.on('end', () => {
63 console.log(mdData);
64 fs.writeFileSync(__dirname + '/web/__md__.json', JSON.stringify(mdData));
65 if (callback) callback(mdData);
66 });
67
68 walker.on('error', (e) => {
69 console.log(e);
70 });
71}
\No newline at end of file