UNPKG

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