2024-03-29 06:29:56 +01:00
|
|
|
import marked from "marked";
|
|
|
|
import express from "express"
|
2024-03-28 19:33:58 +01:00
|
|
|
import ejs from "ejs";
|
2024-03-29 06:29:56 +01:00
|
|
|
import fs from "fs";
|
2024-03-28 19:33:58 +01:00
|
|
|
import path from "path";
|
2024-03-29 10:52:09 +01:00
|
|
|
import jsdom from "jsdom";
|
|
|
|
|
2024-03-28 19:33:58 +01:00
|
|
|
let app = express();
|
2024-03-29 10:52:09 +01:00
|
|
|
|
|
|
|
// set view engine to ejs
|
2024-03-28 19:33:58 +01:00
|
|
|
app.set("view engine", "ejs")
|
|
|
|
app.set('views', path.join(__dirname, 'templates'))
|
|
|
|
|
2024-03-29 10:52:09 +01:00
|
|
|
// type for post object
|
2024-03-28 19:33:58 +01:00
|
|
|
type Post = {
|
|
|
|
file: string;
|
|
|
|
title: string;
|
2024-03-29 10:52:09 +01:00
|
|
|
parsedPost: string;
|
|
|
|
rawPost: string;
|
|
|
|
metadata: fs.Stats;
|
|
|
|
}
|
|
|
|
|
|
|
|
// html stripper, used for title
|
|
|
|
async function htmlstripper(html: string){
|
|
|
|
return new jsdom.JSDOM(html).window.document.body.textContent || " ";
|
2024-03-28 19:33:58 +01:00
|
|
|
}
|
|
|
|
|
2024-03-29 10:52:09 +01:00
|
|
|
// returns Post array
|
|
|
|
async function contentScan(){
|
2024-03-28 19:33:58 +01:00
|
|
|
let posts: Post[] = []
|
2024-03-29 10:52:09 +01:00
|
|
|
let postsDir = path.join(__dirname, "posts")
|
|
|
|
let files = await fs.readdirSync(postsDir).filter((name: string) => name.toLowerCase().endsWith(".md"))
|
|
|
|
for (const file of files) {
|
|
|
|
let postPath = path.join(postsDir, file)
|
|
|
|
let metadata = fs.statSync(postPath)
|
|
|
|
let postContent = fs.readFileSync(postPath, "utf-8")
|
|
|
|
posts.push(
|
|
|
|
{
|
|
|
|
file: file,
|
|
|
|
title: await htmlstripper(
|
|
|
|
await marked.parse(
|
|
|
|
postContent.split("\n")[0]
|
|
|
|
)
|
|
|
|
),
|
|
|
|
metadata: metadata,
|
|
|
|
parsedPost: await marked.parse(postContent),
|
|
|
|
rawPost: postContent
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
2024-03-28 19:33:58 +01:00
|
|
|
return posts;
|
|
|
|
}
|
|
|
|
|
2024-03-29 10:52:09 +01:00
|
|
|
app.get("/", async (req:express.Request,res:express.Response) => {
|
|
|
|
res.render("index", {posts: (await contentScan())})
|
2024-03-28 19:33:58 +01:00
|
|
|
});
|
|
|
|
|
2024-03-29 10:52:09 +01:00
|
|
|
app.use("/post/:post", async (req:express.Request,res:express.Response) => {
|
2024-03-28 19:33:58 +01:00
|
|
|
let pathToPost = path.join(__dirname, "posts", req.params.post);
|
|
|
|
if(!fs.existsSync(pathToPost)) return res.end("404.");
|
2024-03-29 10:52:09 +01:00
|
|
|
let posts = await contentScan();
|
|
|
|
let post = posts.filter(post => post.file === req.params.post)
|
|
|
|
if(!post[0]) return res.end("404.")
|
|
|
|
res.render("post", {posts: posts, post: post[0]})
|
2024-03-28 19:33:58 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
app.listen(3024)
|