UNPKG

2.88 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
12function parseData(arr, page, rank, file) {
13 if (!arr.length) {
14 const files = [];
15 files[rank] = file;
16 arr.push({
17 'page': page,
18 'files': files
19 })
20 return;
21 }
22
23 arr.every(item => {
24 if (item.page == page) {
25 item.files[rank] = file;
26 return false;
27 }
28 return true;
29 });
30}
31
32
33
34module.exports = function walkMD(config, callback) {
35
36 function writeFiles(data) {
37
38 if (fs.existsSync(dist)) sh(`rm -rf ${dist}`);
39 fs.mkdirSync(dist);
40
41 for(var k in data) {
42 const category = data[k];
43 category.forEach(item => {
44 let outFile = '';
45 item.files.forEach(f => {
46 outFile += `require('${f}'),\n`
47 })
48
49 let out = `module.exports = [\n${outFile}]`
50
51 fs.writeFileSync(dist + `/__${item.page}.js`, out);
52 });
53 }
54 }
55
56 const mdData = {};
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 // console.log(file);
66 if (ext === config.ext) {
67 const input = fs.readFileSync(file, 'utf-8');
68 const yaml = yamlFront.loadFront(input, 'content');
69 // console.log(yaml);
70 const page = yaml.page;
71 const rank = yaml.rank;
72 let category = yaml.category;
73
74 if (!category) category = '__default__';
75
76
77 if (!mdData[category]) mdData[category] = [];
78 parseData(mdData[category], page, rank, file);
79 // if (!mdData[title]) mdData[title] = {};
80 // if (!mdData[title].files) mdData[title].files = [];
81 // mdData[title].files[rank] = file;
82 }
83
84 next();
85 });
86
87 walker.on('end', () => {
88 console.log(chalk.green('=========解析markdown========='));
89 console.log(chalk.green(JSON.stringify(mdData)));
90 console.log(chalk.green('=========end========='));
91
92 writeFiles(mdData);
93
94 //将config 写入 文件
95 const data = {
96 md: mdData,
97 config: config
98 }
99 fs.writeFileSync(dist + '/__md__.json', JSON.stringify(data));
100 if (callback) callback(mdData);
101 });
102
103 walker.on('error', (e) => {
104 console.log(e);
105 });
106}
\No newline at end of file