UNPKG

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