UNPKG

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