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