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 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 |
|
27 | function writeFiles(data) {
|
28 |
|
29 | for(var k in data) {
|
30 | const category = data[k];
|
31 | category.forEach(item => {
|
32 | let outFile = '';
|
33 | item.files.forEach(f => {
|
34 | outFile += `require('${f}'),\n`
|
35 | })
|
36 |
|
37 | let out = `module.exports = {${outFile}}`
|
38 |
|
39 | fs.writeFileSync(__dirname + `/tmp/__${item.page}.js`, out);
|
40 | });
|
41 | }
|
42 |
|
43 |
|
44 | }
|
45 |
|
46 |
|
47 | module.exports = function walkMD(config, callback) {
|
48 | const mdData = {};
|
49 |
|
50 | const walker = walk.walk(config.root);
|
51 | walker.on('file', function (root, fileStats, next) {
|
52 | const name = fileStats.name;
|
53 | const ext = path.extname(name);
|
54 | const basename = path.basename(name, config.ext);
|
55 |
|
56 | const file = path.resolve('', root + '/' + name);
|
57 |
|
58 | if (ext === config.ext) {
|
59 | const input = fs.readFileSync(file, 'utf-8');
|
60 | const yaml = yamlFront.loadFront(input, 'content');
|
61 |
|
62 | const page = yaml.page;
|
63 | const rank = yaml.rank;
|
64 | const category = yaml.category;
|
65 |
|
66 | if (!mdData[category]) mdData[category] = [];
|
67 | parseData(mdData[category], page, rank, file);
|
68 |
|
69 |
|
70 |
|
71 | }
|
72 |
|
73 | next();
|
74 | });
|
75 |
|
76 |
|
77 | walker.on('end', () => {
|
78 | console.log(mdData);
|
79 | writeFiles(mdData);
|
80 |
|
81 | if (callback) callback(mdData);
|
82 | });
|
83 |
|
84 | walker.on('error', (e) => {
|
85 | console.log(e);
|
86 | });
|
87 | } |
\ | No newline at end of file |