UNPKG

2.42 kBJavaScriptView Raw
1const fs = require('fs');
2const path = require('path');
3const walk = require('walk');
4const yamlFront = require('yaml-front-matter');
5const sh = require('child_process').execSync;
6
7
8function parseData(arr, page, rank, file) {
9 if (!arr.length) {
10 const files = [];
11 files[rank] = file;
12 arr.push({
13 'page': page,
14 'files': files
15 })
16 return;
17 }
18
19 arr.every(item => {
20 if (item.page == page) {
21 item.files[rank] = file;
22 return false;
23 }
24 return true;
25 });
26}
27
28function writeFiles(data) {
29 const dist = __dirname + '/tmp';
30
31 if (fs.existsSync(dist)) fs.rmdirSync(dist);
32 fs.mkdirSync(dist);
33
34 for(var k in data) {
35 const category = data[k];
36 category.forEach(item => {
37 let outFile = '';
38 item.files.forEach(f => {
39 outFile += `require('${f}'),\n`
40 })
41
42 let out = `module.exports = [\n${outFile}]`
43
44 fs.writeFileSync(dist + `/__${item.page}.js`, out);
45 });
46 }
47
48
49}
50
51
52module.exports = function walkMD(config, callback) {
53 const mdData = {};
54
55 const walker = walk.walk(config.root);
56 walker.on('file', function (root, fileStats, next) {
57 const name = fileStats.name;
58 const ext = path.extname(name);
59 const basename = path.basename(name, config.ext);
60
61 const file = path.resolve('', root + '/' + name);
62 // console.log(file);
63 if (ext === config.ext) {
64 const input = fs.readFileSync(file, 'utf-8');
65 const yaml = yamlFront.loadFront(input, 'content');
66 // console.log(yaml);
67 const page = yaml.page;
68 const rank = yaml.rank;
69 const category = yaml.category;
70
71 if (!mdData[category]) mdData[category] = [];
72 parseData(mdData[category], page, rank, file);
73 // if (!mdData[title]) mdData[title] = {};
74 // if (!mdData[title].files) mdData[title].files = [];
75 // mdData[title].files[rank] = file;
76 }
77
78 next();
79 });
80
81
82 walker.on('end', () => {
83 console.log(mdData);
84 writeFiles(mdData);
85 // fs.writeFileSync(__dirname + '/web/__md__.json', JSON.stringify(mdData));
86 if (callback) callback(mdData);
87 });
88
89 walker.on('error', (e) => {
90 console.log(e);
91 });
92}
\No newline at end of file