使用 Next.js 解析 Markdown 文件数据 - 约 596 字
安装 gray-matter
首先,安装 gray-matter
让我们解析每个 Markdown 文件中的元数据。
注意:这一步其实我们在项目一开始就已经做了,这里就不需要再安装 gray-matter
了,可以跳过安装 gray-matter
这一步。
- 第一篇文章 《 如何使用 Next.js 构建高效的博客网站 》 里我们在 package.json 文件里添加的内容,就已经有
gray-matter
了。
npm install gray-matter
创建实用函数来读取文件系统
接下来,我们将创建一个实用函数来解析文件系统中的数据。有了这个效用函数,我们可以:
- 解析每个 Markdown 文件并获取 title、date 和文件名(将用于 id 发布 URL )。
- 列出索引页上的数据,按日期排序。
在根目录中创建一个名为 lib
的顶级目录。然后,在 lib
中创建一个名为 posts.js
的文件,然后复制并粘贴以下代码:
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
const postsDirectory = path.join(process.cwd(), 'posts');
export function getSortedPostsData() {
// Get file names under /posts
const fileNames = fs.readdirSync(postsDirectory);
const allPostsData = fileNames.map((fileName) => {
// Remove ".md" from file name to get id
const id = fileName.replace(/\.md$/, '');
// Read markdown file as string
const fullPath = path.join(postsDirectory, fileName);
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,
};
});
// Sort posts by date
return allPostsData.sort((a, b) => {
if (a.date < b.date) {
return 1;
} else {
return -1;
}
});
}
笔记:
学习
Next.js
不需要看懂上面的代码是干什么的,作用就是让博客例子功能化。但如果您想了解更多:
- fs 是一个 Node.js 模块,可让您从文件系统中读取文件。
- path 是一个 Node.js 模块,可让您操作文件路径。
- matter 是一个库,可让您解析每个降价文件中的元数据。
- 在 Next.js 中,lib 文件夹没有像 pages 文件夹那样的指定名称,因此您可以随意命名。通常习惯使用 lib or utils。
获取博客数据
现在已经解析了博客数据,我们需要将它添加到我们的索引页面 ( pages/index.js )。我们可以使用名为 的 Next.js 数据获取方法来完成此操作 getStaticProps()
。在下一节中,我们将学习如何实现 getStaticProps()
。