Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
262 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
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 id | ||
const id = 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 matterResult = matter(fileContents) | ||
|
||
// Combine the data with the id | ||
return { | ||
id, | ||
...matterResult.data | ||
} | ||
}) | ||
// Sort posts by date | ||
return allPostsData.sort(({ date: a }, { date: b }) => { | ||
if (a < b) { | ||
return 1 | ||
} else if (a > b) { | ||
return -1 | ||
} else { | ||
return 0 | ||
} | ||
}) | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
05d1290
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops