UNPKG

3.19 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
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 source[item.page] = path.resolve(__dirname, '../theme/tmp', `__${item.page}`);
53
54 fs.writeFileSync(dist + `/__${item.page}.js`, out);
55 });
56 }
57 }
58
59 const mdData = {};
60 const source = {};
61
62 const walker = walk.walk(config.root);
63 walker.on('file', function (root, fileStats, next) {
64 const name = fileStats.name;
65 const ext = path.extname(name);
66 const basename = path.basename(name, config.ext);
67
68 const file = path.resolve('', root + '/' + name);
69 // console.log(file);
70 if (ext === config.ext) {
71 const input = fs.readFileSync(file, 'utf-8');
72 const yaml = yamlFront.loadFront(input, 'content');
73 // console.log(yaml);
74 const page = yaml.page;
75 const rank = yaml.rank;
76 let category = yaml.category;
77
78 if (!category) category = '__default__';
79
80
81 if (!mdData[category]) mdData[category] = [];
82 parseData(mdData[category], page, rank, file);
83 // if (!mdData[title]) mdData[title] = {};
84 // if (!mdData[title].files) mdData[title].files = [];
85 // mdData[title].files[rank] = file;
86 }
87
88 next();
89 });
90
91 walker.on('end', () => {
92 console.log(chalk.green('=========解析markdown========='));
93 console.log(chalk.green(JSON.stringify(mdData, null, 4)));
94 console.log(chalk.green('=========end========='));
95
96 writeFiles(mdData);
97
98 //将config 写入 文件
99 const data = {
100 md: mdData,
101 config: config,
102 source: source,
103 // root: process.cwd()
104 }
105 fs.writeFileSync(dist + '/__md__.json', JSON.stringify(data, null, 4));
106 if (callback) callback(mdData);
107 });
108
109 walker.on('error', (e) => {
110 console.log(e);
111 });
112}
\No newline at end of file