forked from anoma/anoma-blog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preview.js
123 lines (110 loc) · 3.1 KB
/
preview.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import fs from "fs";
import path from "path";
import minimist from "minimist";
import chalk from "chalk";
import open from "open";
import frontMatter from "front-matter";
import cors from "cors";
import express from "express";
import { parsePostContent, createPostPreview } from "./.scripts/posts.js";
const args = minimist(process.argv.slice(2));
const filename = args["f"] ?? args["_"][0];
const mediaDir = path.dirname(filename);
const httpPort = args["p"] ?? 8110;
const httpUrl = `http://localhost:${httpPort}/`;
const anomaUrl = "https://anoma.net/blog/preview";
const replaceSrcPath = (content) => {
return content.replace(/src="/gi, `src="${httpUrl}/`);
};
const httpConsole = (message) => chalk.blue(message);
// Welcome!
console.log(chalk.bgRed(chalk.white(" Anoma Blog - Preview ")));
// Check if file argument was provided
if (!filename) {
console.log(
chalk.bgRed(
"File path was not provided. Please call preview.js script as `node preview.js <filename>`",
),
);
process.exit(1);
}
// Check if the provided filepath exists
if (!fs.existsSync(filename)) {
console.log(
chalk.bgRed(
"Invalid file provided. Please check if the following path is correct: " +
filename,
),
);
process.exit(1);
}
// Starting HTTP server using express
console.log(chalk.bgBlueBright(` Starting HTTP Server on port ${httpPort} `));
const app = express();
let sseResponse;
app.use(
cors({
origin: "*",
methods: ["GET", "OPTIONS"],
allowedHeaders: ["Content-Type"],
}),
);
app.use(express.static(mediaDir));
app.listen(httpPort, () => {
console.log(
httpConsole(`HTTP Server listening to http://localhost:${httpPort}`),
);
watchFileForChanges();
console.log(
httpConsole(`Please access the following URL on Firefox: ${anomaUrl}`),
);
open(anomaUrl);
});
app.get("/events", (req, res) => {
sseResponse = res;
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
update(res);
req.on("close", () => res.end());
});
const parseFileUpdates = async (filename) => {
const updatedContents = fs.readFileSync(filename, "utf8");
const { attributes } = frontMatter(updatedContents);
const postInfo = createPostPreview(filename.replace(".md", ""), attributes);
const postContent = replaceSrcPath(await parsePostContent(filename));
return { postInfo, postContent, attributes };
};
const sendUpdatedBlogInfo = async (
res,
{ attributes, postContent, postInfo },
) => {
const msg = JSON.stringify({
...postInfo,
image: httpUrl + "/" + attributes.image,
content: postContent,
});
console.log(
chalk.gray(
`[${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}]`,
) + httpConsole(` Updating Preview`),
);
res.write(`data: ${msg}\n\n`);
};
const watchFileForChanges = () => {
fs.watchFile(
filename,
{
persistent: true,
interval: 200,
},
() => {
if (sseResponse) {
update(sseResponse);
}
},
);
};
async function update(res) {
sendUpdatedBlogInfo(res, await parseFileUpdates(filename));
}