丰富内容

This commit is contained in:
cheney
2026-04-06 09:11:22 +08:00
parent a2bec07322
commit 620e46661f
14 changed files with 550 additions and 3 deletions
+52
View File
@@ -0,0 +1,52 @@
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
}
}