Skip to content

Instantly share code, notes, and snippets.

@AlissonSteffens
Created October 5, 2022 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlissonSteffens/d6c008255d2e79eb86ad35412e0f1dff to your computer and use it in GitHub Desktop.
Save AlissonSteffens/d6c008255d2e79eb86ad35412e0f1dff to your computer and use it in GitHub Desktop.
NextJS get markdown files in folder as data (properties) and content
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