Skip to content

Instantly share code, notes, and snippets.

@allpwrfulroot
Last active December 12, 2019 14:24
Show Gist options
  • Save allpwrfulroot/2705b7dd86f0056676d5e893474aeef4 to your computer and use it in GitHub Desktop.
Save allpwrfulroot/2705b7dd86f0056676d5e893474aeef4 to your computer and use it in GitHub Desktop.
Demo utility function for directory introspection and data collection
const fs = require('fs')
const { promisify } = require('util')
const YAML = require('yaml')
async function getMDXInfo(content) {
try {
const files = await promisify(fs.readdir)(`./pages/${content}`)
const mdx = await files.filter(f => f.includes('.mdx'))
let list = await Promise.all(
mdx.map(async p => {
let meta = {}
let name = p.replace('.mdx', '')
let { size } = await promisify(fs.stat)(`./pages/${content}/${p}`)
let page = await promisify(fs.readFile)(`./pages/${content}/${p}`)
let frontmatter = page.toString().split('---')[1]
if (frontmatter) {
meta = YAML.parse(frontmatter)
}
return {
name,
size,
...meta,
}
})
)
await list.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
return { list }
} catch (error) {
console.log('err in getMDXInfo: ', error)
throw new Error('Project data unavailable')
}
}
async function writeMDXInfo(content) {
try {
const { list } = await getMDXInfo(content)
await promisify(fs.writeFile)(
`./pages/${content}/${content}-list.json`,
JSON.stringify(list)
)
} catch (err) {
console.log('error in writeMDXInfo: ', err)
}
}
module.exports = {
getMDXInfo,
writeMDXInfo,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment