70 %

Toast is in Beta!Learn more →

Chris Biscardi

Convert MDX with Frontmatter to MDX with Exports

A script to convert MDX with frontmatter to MDX with an export.

// node fs comes with promises now
const fs = require("fs").promises;
// front-matter is what we used in gatsby-plugin-mdx to parse out frontmatter
const fm = require("front-matter");
const dir = "./a-directory";
// node doesn't allow top-level async/await yet, so we make it a function
// and then call it
async function run() {
// read the filenames in the relevant directory.
const files = await fs.readdir(dir, "utf-8");
await Promise.all(
.filter(name => name.endsWith("mdx"))
.map(async filename => {
// if we don't use `utf-8` we get a buffer
const file = await fs.readFile(`${dir}/${filename}`, "utf-8");
// attributes are the json representation of the frontmatter
// body is everything else
const { attributes, body } = fm(file);
// grab the json representation of the frontmatter and export it
// as the identifier meta
const content = `export const meta = ${JSON.stringify(
// write the file back out
await fs.writeFile(`${dir}/${filename}`, content, "utf-8");
// return content but it doesn't matter because we don't use it
return content;