jabe/index.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-03-29 06:29:56 +01:00
import marked from "marked";
import express from "express"
import ejs from "ejs";
2024-03-29 06:29:56 +01:00
import fs from "fs";
import path from "path";
2024-03-29 10:52:09 +01:00
import jsdom from "jsdom";
2024-03-29 13:51:20 +01:00
import config from "./config.json"
2024-03-29 10:52:09 +01:00
let app = express();
2024-03-29 10:52:09 +01:00
// set view engine to ejs
app.set("view engine", "ejs")
app.set('views', path.join(__dirname, 'templates'))
2024-03-29 10:52:09 +01:00
// type for post object
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-29 10:52:09 +01:00
// returns Post array
async function contentScan(){
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
}
)
}
return posts;
}
2024-03-29 10:52:09 +01:00
app.get("/", async (req:express.Request,res:express.Response) => {
2024-03-29 13:51:20 +01:00
res.render("index", {posts: (await contentScan()), config: config})
});
2024-03-29 10:52:09 +01:00
app.use("/post/:post", async (req:express.Request,res:express.Response) => {
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.")
2024-03-29 13:51:20 +01:00
res.render("post", {posts: posts, post: post[0], config: config})
})
app.listen(3024)