iboard/utils/articleUtils.js
2026-04-06 09:11:22 +08:00

53 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}
}