UNPKG

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