UNPKG

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