UNPKG

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