UNPKG

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