mirror of
https://github.com/vercel/next-learn.git
synced 2026-06-11 09:51:47 +00:00
36 lines
894 B
JavaScript
36 lines
894 B
JavaScript
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 slug
|
|
const slug = 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 { data } = matter(fileContents)
|
|
|
|
// Combine the data with the slug
|
|
return {
|
|
slug,
|
|
...data
|
|
}
|
|
})
|
|
// Sort posts by date
|
|
return allPostsData.sort((a, b) => {
|
|
if (a.date < b.date) {
|
|
return 1
|
|
} else {
|
|
return -1
|
|
}
|
|
})
|
|
}
|