import fs from 'fs' import path from 'path' import matter from 'gray-matter' export function getArticles() { const articlesDirectory = path.join(process.cwd(), 'content', 'articles') const fileNames = fs.readdirSync(articlesDirectory) const articles = fileNames .filter(fileName => fileName.endsWith('.md')) .map(fileName => { const fullPath = path.join(articlesDirectory, fileName) const fileContents = fs.readFileSync(fullPath, 'utf8') const { data, content } = matter(fileContents) // 从文件名中提取日期(假设文件名格式为 YYYY-MM-DD-article-title.md) const dateMatch = fileName.match(/^(\d{4}-\d{2}-\d{2})-/) const date = dateMatch ? dateMatch[1] : '' // 提取简介(前150个字符) const excerpt = content.substring(0, 150) + '...' return { id: fileName.replace('.md', ''), date, title: data.title || fileName.replace(/\d{4}-\d{2}-\d{2}-/, '').replace('.md', ''), excerpt, content } }) // 按日期排序,最近的优先 return articles.sort((a, b) => { if (a.date && b.date) { return new Date(b.date) - new Date(a.date) } return 0 }) } export function getPagedArticles(page = 1, pageSize = 5) { const allArticles = getArticles() const startIndex = (page - 1) * pageSize const endIndex = startIndex + pageSize return { articles: allArticles.slice(startIndex, endIndex), total: allArticles.length, totalPages: Math.ceil(allArticles.length / pageSize), currentPage: page } }