forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate_epub_toc.js
More file actions
25 lines (20 loc) · 830 Bytes
/
generate_epub_toc.js
File metadata and controls
25 lines (20 loc) · 830 Bytes
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
const {readFileSync} = require("fs")
const {basename} = require("path")
let [template, ...chapters] = process.argv.slice(2)
function esc(str) {
return str.replace(/[<>&"]/g, ch => ch == "<" ? "<" : ch == ">" ? ">" : ch == "&" ? "&" : """)
}
let toc = ""
const section = /<h2\b[^>]*><a [^>]*?id="(h_.*?)".*?><\/a>(.*?)<\/h2>/g
for (let chapter of chapters) {
let text = readFileSync(chapter, "utf8")
let base = basename(chapter)
let title = /<h1.*?>(.*?)<\/h1>/.exec(text)[1]
toc += ` <li><a href="${base}">${esc(title)}</a>
<ol>\n`
for (let match; match = section.exec(text);)
toc += ` <li><a href="${base}#${match[1]}">${esc(match[2])}</a></li>\n`
toc += ` </ol>
</li>\n`
}
console.log(readFileSync(template, "utf8").replace("{{full_toc}}", toc))