import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
const postsDirectory = path.join(process.cwd(), 'posts');
//
...
...
...
//
export function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents);
// Combine the data with the id
return {
id,
...matterResult.data,
};
}
What does matter do in gray-matter in node js?
I am trying dynamic routing in Next.js, please explain the use of the matter() function.
You can read the documentation of the package.
You will see an example listend there:
Converts a string with front-matter, like this:
---
title: Hello
slug: home
---
<h1>Hello world!</h1>
Into an object like this:
{
content: '<h1>Hello world!</h1>',
data: {
title: 'Hello',
slug: 'home'
}
}