-
Notifications
You must be signed in to change notification settings - Fork 8
/
generate_html.js
90 lines (69 loc) · 2.02 KB
/
generate_html.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const fs = require('fs')
const path = require('path')
const marked = require('marked')
function readRootDir() {
return new Promise(resolve => {
fs.readdir('./', (err, files) => {
resolve(files)
})
})
}
function getPromiseArr(files) {
const promiseArr = []
// 遍历章
files.forEach(file => {
// 排除 node_modules 和 .git 两个文件夹的干扰
if (file === 'node_modules' || file === '.git') return
let path1 = path.join(__dirname, file)
let stats = fs.statSync(path1)
// 排除类似 generate.js package.json 等文件的干扰
if (!stats.isDirectory()) return
promiseArr.push(new Promise(resolve => {
const chapter = {
chapterName: file, // 章节名
sections: [] // 子章节名
}
fs.readdir(path1, (err, files) => {
// 遍历节
files.forEach(file => {
if (!file.endsWith('.html')) return
chapter.sections.push(file)
})
resolve(chapter)
})
}))
})
return promiseArr
}
function generateMarkdown(res) {
res.sort((a, b) => a.chapterName > b.chapterName)
let markdownStr = ''
let urlPrefix = `/`
markdownStr += `# CSS SECRETS\n\n`
res.forEach(chapter => {
let {chapterName, sections} = chapter
markdownStr += `## ${chapterName}\n\n`
sections.sort()
sections.forEach(sectionName => {
let url = urlPrefix + chapterName + '/' + sectionName
url = encodeURI(url)
markdownStr += `- [${sectionName.replace('.html', '')}](${url})\n`
})
markdownStr += '\n'
})
let htmlStr = marked(markdownStr)
// 新标签打开
htmlStr += `
<script>document.querySelectorAll('a').forEach(item => { item.setAttribute('target', '_blank') })</script>
`
fs.writeFile('index.html', htmlStr, () => {
console.log('index.html saved!')
})
}
(async function() {
const files = await readRootDir()
const promiseArr = getPromiseArr(files)
Promise.all(promiseArr).then(res => {
generateMarkdown(res)
}).catch((err) => {console.log(err)})
})()