TIL: Gray Matter NPM

First TIL

In working with the blog template for nextjs, I found a package that is so dumb-simple and I love it.

"gray-matter" on npm will parse a string (usually from a file), and turn some "front matter" into a plain old javascript object. The "front matter" can be yml, which is a bit lighter for typists to jam out quickly and allows for pairing your content with the structured data.

Very useful for the flat-file pattern that drives the blog you're reading right now!


  import matter from "gray-matter";

  const fullPath = join(directory, filename);
  const fileContents = fs.readFileSync(fullPath, "utf8");
  const { data, content } = matter(fileContents);

An example of a file with some structured data at the top in yml looks like this:

---
author:
  name: Teddy
  nickname: Bear

date: "2020-05-13T02:38:20.665Z"

---

Now this is the blog post! This is generally unstructured part of the
content that Gray Matter returns in { content }.
The part above this has "---" surrounding the structured part.
That's what Gray Matter will interpret for you, and return as { data }.

Since we're using yml here, you even get a cool structured object out of the "author" property, which returns from the parser as "data.author.name" and "data.author.nickname".