UNPKG

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