Last active
January 13, 2025 17:36
-
-
Save christiannaths/71c7faff902cd132d0ebc3b7e5441eab to your computer and use it in GitHub Desktop.
Read a directory for .md files and parse them into blog posts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ./lib/blog.ts | |
import fs from "fs"; | |
import matter from "gray-matter"; | |
import md from "markdown-it"; | |
const MARKDOWN_PATH = "public/articles"; | |
type PostMetadata = { | |
slug: string; | |
title: string; | |
description: string; | |
date: string; | |
author: string; | |
authorImage: string; | |
previewImage: string; | |
}; | |
type Post = { | |
metadata: PostMetadata; | |
content: string; | |
}; | |
export function getPost(slug: string): Post { | |
const readFile = fs.readFileSync(`${MARKDOWN_PATH}/${slug}.md`, "utf-8"); | |
const { data, content } = matter(readFile); | |
const { title, description, previewImage, date, author, authorImage } = data; | |
return { | |
metadata: { | |
slug, | |
title, | |
description, | |
date, | |
author, | |
authorImage, | |
previewImage, | |
}, | |
content: md().render(content), | |
}; | |
} | |
export function getPosts() { | |
const files = fs.readdirSync(MARKDOWN_PATH); | |
const posts = files.map((fileName) => { | |
const slug = fileName.replace(".md", ""); | |
return getPost(slug); | |
}); | |
return posts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment