Created
October 5, 2022 02:33
-
-
Save AlissonSteffens/d6c008255d2e79eb86ad35412e0f1dff to your computer and use it in GitHub Desktop.
NextJS get markdown files in folder as data (properties) and content
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
export function getDocBySlug(dir, slug, fields = []) { | |
const realSlug = slug.replace(/\.md$/, ''); | |
const fullPath = join('/base/', `${realSlug}.md`); | |
const fileContents = fs.readFileSync(fullPath, 'utf8'); | |
const { data, content } = matter(fileContents); | |
console.log(data, content); | |
const items = {}; | |
// Ensure only the minimal needed data is exposed | |
fields.forEach((field) => { | |
if (field === 'slug') { | |
items[field] = realSlug; | |
} | |
if (field === 'content') { | |
items[field] = content; | |
} | |
if (data[field]) { | |
items[field] = data[field]; | |
} | |
} | |
); | |
return items; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment