-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmd2html.js
More file actions
70 lines (61 loc) · 1.75 KB
/
md2html.js
File metadata and controls
70 lines (61 loc) · 1.75 KB
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
const fs = require('fs')
const path = require('path')
const MarkdownIt = require('markdown-it')
const sourceDir = path.join(__dirname, 'samples') // source directory of .md
const outputDir = path.join(__dirname, 'output') // output directory of .html
// recursively mkdir
const rmkdir = p => {
p
.split('/')
.reduce((p, folder) => {
p += folder + '/'
if (!fs.existsSync(p)) {
fs.mkdirSync(p)
}
return p
}, '')
}
// get relative path for writing html
const getRelativePath = filePath => {
const dir = path.dirname(filePath)
return dir.substr(sourceDir.length, dir.length)
}
// read md, write html
const md2html = filename => {
fs.readFile(filename, 'utf-8', (err, data) => {
if (err) throw new Error(err)
let output
let md = new MarkdownIt({ // MarkdownIt options
html: true,
xhtmlOut: false,
typographer: true,
linkify: true
})
try {
output = md.render(data)
} catch (e) {
throw new Error(err)
}
const absolutePath = path.join(outputDir, getRelativePath(filename))
if (!fs.existsSync(absolutePath)) {
rmkdir(absolutePath)
}
const basename = path.basename(filename, '.md')
fs.writeFileSync(path.join(absolutePath, `${basename}.html`), output)
})
}
const walk = (dir, spaces = '--') => {
fs.readdir(dir, (err, stuff) => {
if (err) throw new Error(err)
stuff.forEach(e => {
if (fs.lstatSync(path.join(dir, e)).isFile() && path.extname(e) === '.md') {
console.log(`${spaces} ${e}`)
md2html(path.join(dir, e))
} else if (fs.lstatSync(path.join(dir, e)).isDirectory()) {
console.log(`${spaces} ${e}\\`)
walk(path.join(dir, e), spaces + '--')
}
})
})
}
walk(sourceDir)