-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontent-builder.js
68 lines (61 loc) · 1.87 KB
/
content-builder.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
const fs = require('fs').promises
const path = require('path')
const { StatWriter } = require('directory-stat')
const { StatCollector } = require('directory-stat/stat-collectors')
const { Converter } = require('showdown')
const fm = require('front-matter')
const highlight = require('showdown-highlight')
const footnotes = require('showdown-footnotes')
const getBodyHtml = (body) => {
const converter = new Converter({
omitExtraWLInCodeBlocks: true,
ghCompatibleHeaderId: true,
simplifiedAutoLink: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tasklists: true,
smartIndentationFix: true,
disableForced4SpacesIndentedSublists: true,
simpleLineBreaks: true,
requireSpaceBeforeHeadingText: true,
openLinksInNewWindow: true,
emoji: true,
extensions: [highlight, footnotes]
})
return converter.makeHtml(body)
}
class BlogPostMetaCollector extends StatCollector {
constructor() {
super('meta')
}
async collect(pathStr, stat) {
if (!stat.isFile()) return undefined
if (path.extname(pathStr).toLowerCase() !== '.md') return undefined
const { attributes: meta, body } = fm(await fs.readFile(pathStr, { encoding: 'utf8' }))
// side effect
let bodyHtml
if (!meta.type || meta.type === 'article') {
bodyHtml = getBodyHtml(body)
}
const { dir, name } = path.parse(pathStr)
try {
fs.writeFile(path.join(dir, `${name}.json`), JSON.stringify({ bodyHtml, ...meta }))
} catch (err) {
console.error('Error while converting .md to .json')
}
return meta
}
}
try {
const sw = new StatWriter(path.join(__dirname, 'content'), {
depth: 1,
exclude: ['.dirstat.json', '*.json'],
minified: true,
output: '.dirstat.json',
statCollectors: [new BlogPostMetaCollector()]
})
sw.export()
} catch (err) {
console.error('Failed to build content')
}