Created
March 16, 2023 16:01
-
-
Save tommymalmqvist/3820bdfbbe55af506eba275b52222c11 to your computer and use it in GitHub Desktop.
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
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((a, b) => { | |
if (a.date < b.date) { | |
return 1; | |
} else { | |
return -1; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment