UNPKG

3 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, category, page, rank, file) {
20 const key = category + "_" + page;
21 if (!arr.length) {
22 const files = [];
23 files[rank] = file;
24 arr.push({
25 'page': page,
26 'files': files
27 })
28 return;
29 }
30
31 arr.every(item => {
32 if (item.page == page) {
33 item.files[rank] = file;
34 return false;
35 }
36 return true;
37 });
38 }
39
40 function writeFiles(data) {
41 for(var k in data) {
42 const category = data[k];
43 category.forEach(item => {
44 const page = item.page;
45 let outFile = '';
46 item.files.forEach(f => {
47 outFile += `require('${f}'),\n`;
48 })
49
50 source[page] = `./tmp/__${page}`;
51
52 const out = `module.exports = [\n${outFile}]`;
53 fs.writeFileSync(dist + `/__${page}.js`, out);
54 });
55 }
56 }
57
58 const walker = walk.walk(config.root);
59 walker.on('file', function (root, fileStats, next) {
60 const name = fileStats.name;
61 const ext = path.extname(name);
62 const basename = path.basename(name, config.ext);
63
64 const file = path.resolve('', root + '/' + name);
65 if (ext === config.ext) {
66 const input = fs.readFileSync(file, 'utf-8');
67 const yaml = yamlFront.loadFront(input, 'content');
68 // console.log(yaml);
69 const page = yaml.page;
70 const rank = yaml.rank;
71 let category = yaml.category;
72
73 if (!category) category = '__default__';
74
75 if (category !== '__nav__') {
76 if (!mdData[category]) mdData[category] = [];
77 parseData(mdData[category], category, page, rank, file);
78 }
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