Skip to content

Instantly share code, notes, and snippets.

@bramses
Last active April 5, 2024 04:38
Show Gist options
  • Select an option

  • Save bramses/2f56a902fb6381c4d66e93d079f20474 to your computer and use it in GitHub Desktop.

Select an option

Save bramses/2f56a902fb6381c4d66e93d079f20474 to your computer and use it in GitHub Desktop.
upserting a markdown file from obsidian into mdx for nextjs
const { read } = require("gray-matter");
const { writeFileSync } = require('fs')
const HOMEPAGE_PATH = process.env.HOMEPAGE_PATH;
/*
This code is taking the markdown file and converting it to a mdx file
The frontmatter data is being extracted from the markdown file then converted into an object.
Then we are checking if there\'s a slug in the frontmatter or not.
If there isn\'t one throw an error because that means we can\'t create a post without a slug
*/
const upsertPost = async (filePath) => {
const markdown = read(filePath);
const frontmatter = markdown.data;
const markdownBody = markdown.content;
const slug = frontmatter.slug;
if (!slug) {
throw new Error('No slug found in frontmatter');
}
const file = `${HOMEPAGE_PATH}/_posts/${slug}.mdx`;
const event = new Date();
let published, featured;
if (frontmatter.published) {
published = frontmatter.published;
} else {
published = true;
}
if (frontmatter.featured) {
featured = frontmatter.featured;
} else {
featured = false;
}
const mdx = `---
title: ${frontmatter.title}
featured: ${featured}
published: ${published}
ogSlug: '${slug}'
ogImageUrl: '${frontmatter.ogImageUrl}'
coverImage: '${frontmatter.ogImageUrl}'
date: '${event.toISOString()}'
excerpt: '${frontmatter.excerpt}'
---
# ${frontmatter.title}
${markdownBody}`;
writeFileSync(file, mdx);
return { slug };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment