-
Notifications
You must be signed in to change notification settings - Fork 3
/
readMDFile.js
36 lines (33 loc) · 1.2 KB
/
readMDFile.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
const fs = require("fs");
const html = require("./generateHTML");
const path = require("path");
let body = "";
module.exports.readMDFile = function (
inputPath,
cssLink,
language,
outputContainer
) {
try {
const data = fs.readFileSync(inputPath, "utf8");
body = data
// Search for all occurences of Markdown links and replace them with the corresponding <a> tags.
.replace(/(?<!!)\[(.*?)\]\((.*?)\)/gim, "<a href='$2'>$1</a>")
.split(/\r?\n\r?\n/)
.map((para) => {
// For each "paragraph", search for any occurence of Markdown heading (# [string] or ## [string]) and replace them with the corresponding HTML header tag (h1 or h2). If heading not found, replace the "paragraph" with <p> tag.
if (para.startsWith("# ")) {
return `<h1>${para.replace(/# /, "")}</h1>\n\n`;
} else if (para.startsWith("## ")) {
return `<h2>${para.replace(/# /, "")}</h2>\n\n`;
}
return `<p>${para.replace(/\r?\n/, " ")}</p>\n\n`;
})
.join(" ");
} catch (err) {
console.error(err);
}
const title = path.basename(inputPath, ".md");
html.generateHTML(language, title, cssLink, body, outputContainer);
return title;
};