我在nodejs / nextjs中工作,我可以访问文件系统。我的文件夹中有多个 React 文件:
content
- blog-post-1.jsx
- blog-post-2.jsx
- blog-post-3.jsx
我现在想要浏览此文件夹中的文件并提取每个文件的 frontmatter。我正在考虑从每个文件中导出一个 javascript 对象,例如:
// e.g.: blog-post-1.jsx
export const frontmatter = {
title: "My Title",
published: "02/12/2024"
}
但我被困在这里: 在不知道
content
文件夹中文件的确切数量的情况下,如何映射文件夹并自动从每个文件中获取 frontmatter 对象?
您可以使用
fs.readdir
来迭代内容目录中的文件。以及 require()
从文件中获取数据。
import fs from 'fs';
import path from 'path';
const folderPath = path.join(__dirname, 'content');
fs.readdir(folderPath, (err, files) => {
if (err) return;
const jsxFiles = files.filter(file => file.endsWith('.jsx'));
jsxFiles.forEach(file => {
const filePath = path.join(folderPath, file);
const { frontmatter } = require(filePath);
console.log(frontmatter);
});
});