Skip to content

Instantly share code, notes, and snippets.

@digitarald
Created August 10, 2021 03:52
Show Gist options
  • Save digitarald/0c75473ecefb92ddecd565c4cd17efff to your computer and use it in GitHub Desktop.
Save digitarald/0c75473ecefb92ddecd565c4cd17efff to your computer and use it in GitHub Desktop.
import fs from "fs";
import path from "path";
import matter from "gray-matter";
import { bundleMDX } from "mdx-bundler";
export const POSTS_PATH = path.join(process.cwd(), "data/_posts");
export const getSourceOfFile = (fileName) => {
return fs.readFileSync(path.join(POSTS_PATH, fileName));
};
export const getAllPosts = () => {
return fs
.readdirSync(POSTS_PATH)
.filter((path) => /\.mdx?$/.test(path))
.map((fileName) => {
const source = getSourceOfFile(fileName);
const slug = fileName.replace(/\.mdx?$/, "");
const { data } = matter(source);
return {
frontmatter: data,
slug: slug,
};
});
};
export const getSinglePost = async (slug) => {
const source = getSourceOfFile(slug + ".mdx");
const { code, frontmatter } = await bundleMDX(source, {
cwd: POSTS_PATH,
});
return {
frontmatter,
code,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment