Markdown files are a staple in the world of documentation, blogging, and static site generation. They offer a simple and readable format for content, but sometimes we need more than just plain text. Metadata, often called front matter, allows us to store additional information at the top of our markdown files. This metadata can include details like the title, date, author, and more. In this post, I’ll walk you through how to open a markdown file in TypeScript and access its metadata, leveraging the powerful gray-matter
library.
Thank me by sharing on Twitter 🙏
Prerequisites
Before we dive into the code, make sure you have Node.js and npm (or yarn) installed on your machine. This guide assumes you have a basic understanding of TypeScript and how to run TypeScript files.
1. Installing gray-matter
The first step in our journey is to install the gray-matter
library, which will help us parse the front matter from our markdown files. This library is straightforward and efficient, making it an excellent choice for our task.
Step 1: Install gray-matter
Open your terminal and run the following command to install gray-matter
using npm:
npm install gray-matter
Alternatively, if you prefer yarn, you can use:
The Nvidia Way: Jensen Huang and the Making of a Tech Giant
$17.50 (as of January 23, 2025 11:35 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)The Technological Republic: Hard Power, Soft Belief, and the Future of the West
$27.00 (as of January 23, 2025 11:35 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)HP 67 Black/Tri-color Ink Cartridges (2 Pack) | Works with HP DeskJet 1255, 2700, 4100 Series, HP ENVY 6000, 6400 Series | Eligible for Instant Ink | 3YP29AN
$36.89 (as of January 23, 2025 11:35 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)yarn add gray-matter
With gray-matter
installed, we’re ready to start coding.
2. Setting Up Your TypeScript Environment
To keep things simple, I’ll assume you already have a TypeScript project set up. If not, you can easily create one using tsc --init
. Let’s focus on creating a TypeScript file that will handle reading and parsing our markdown files.
Step 2: Create Your TypeScript File
Create a new TypeScript file, for example, parseMarkdown.ts
. This file will contain all the logic for reading the markdown file and extracting its metadata.
Step 3: Import Required Modules
At the top of your parseMarkdown.ts
file, import the necessary modules:
import * as fs from 'fs';
import * as path from 'path';
import matter from 'gray-matter';
3. Reading the Markdown File
Now that we have our modules imported, the next step is to read the markdown file. We’ll use Node’s built-in fs
module to handle file reading.
Step 4: Define the Path to Your Markdown File
Specify the path to your markdown file. For this example, let’s assume our markdown file is named example.md
and is located in the same directory as our TypeScript file.
const markdownFilePath = path.join(__dirname, 'example.md');
Step 5: Read the File Content
Use fs.readFileSync
to read the content of the markdown file:
const fileContent = fs.readFileSync(markdownFilePath, 'utf-8');
4. Parsing the Markdown File with gray-matter
With the file content in hand, the next step is to parse it using gray-matter
. This library makes it incredibly easy to extract the front matter and the markdown content.
Step 6: Parse the Markdown File
Use the matter
function from gray-matter
to parse the file content:
const { data: metadata, content } = matter(fileContent);
Here, metadata
will contain the front matter as an object, and content
will contain the rest of the markdown content as a string.
Step 7: Logging the Metadata and Content
To verify everything is working as expected, log the metadata and content to the console:
console.log('Metadata:', metadata);
console.log('Content:', content);
5. Example Markdown File
For this example, let’s use a markdown file with the following content:
---
title: "My Markdown File"
date: "2024-07-07"
author: "Your Name"
---
# This is the content of the markdown file
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
6. Running Your TypeScript File
Finally, let’s run our TypeScript file to see everything in action. We will use tsx
to run the TypeScript file directly without needing to compile it manually.
Step 8: Install tsx
First, install tsx
globally:
npm install -g tsx
Step 9: Run Your TypeScript File
Now, you can run your TypeScript file directly using the tsx
command:
tsx parseMarkdown.ts
You should see the metadata and content logged to the console:
Metadata: { title: 'My Markdown File', date: '2024-07-07', author: 'Your Name' }
Content:
# This is the content of the markdown file
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Conclusion
And there you have it! We’ve successfully opened a markdown file in TypeScript and accessed its metadata using gray-matter
. This approach is incredibly powerful and can be extended to suit a variety of use cases, such as building static site generators, blogging platforms, or even just organizing your personal documentation.
By leveraging TypeScript and gray-matter
, we can efficiently manage and utilize metadata within our markdown files, opening up a world of possibilities for automation and content management. Happy coding!