-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.mjs
executable file
·64 lines (53 loc) · 1.59 KB
/
main.mjs
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
#! node
import { getConfig } from "./config.mjs";
import { server } from "./server.mjs";
import { fileReader } from "./fileReader.mjs";
import { parse } from "./markdownParser.mjs";
import { readFileSync, createReadStream } from "node:fs";
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const config = getConfig();
let html = "";
const css = readFileSync(`${__dirname}/style.css`, { encoding: "utf8" });
const template = [`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>${css}</style>
</head>
<body>`, `</body>`];
function assignHtml(body) {
html = template.join(body);
}
if (config.watch) {
fileReader(config.input, (err, markdown) => {
if (err) {
console.error(err);
return;
}
assignHtml(parse(markdown));
});
}
else {
fileReader(config.input)
.then(parse)
.then(assignHtml);
}
config.port = config.port || Math.floor(Math.random() * 50000 + 3000);
server(config.port, (req, res) => {
if (req.url === "/") {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.end(html);
return;
}
const fileStream = createReadStream(`.${req.url}`);
fileStream.on("open", () => fileStream.pipe(res));
fileStream.on("error", (err) => { console.error(err); res.writeHead(404); res.end(); });
}).then((...args) => {
console.log(`\nLintening on http://localhost:${config.port}`);
}).catch(console.error);