const fs = require('fs') const path = require('path') const markdownit = require('markdown-it') const md = markdownit({ html: true, breaks: true, typographer: { whitespace: 'all' }, }) const logger = require('./logger')() // Parse markdown class Blog { constructor() {} async ReadBlogs() {return this.#LoadBlogs().then(output => {return output})} // ! Check if file is a markdown file async #LoadBlogs() { return new Promise((res, rej) => { if (fs.existsSync('./blog/')) { fs.readdir('./blog/', (err, files) => { if (err) { logger.Error(`${err.code}: Error reading directory`) rej(`${err.code}: Error reading directory`) } else { this.blog = new Map() files.forEach(file => { this.blog.set(file.replace('.md', ''), fs.readFileSync(path.resolve(`./blog/${file}`), 'utf-8', (err, data) => { if (err) { logger.Error(`${err.code}: Failed to read ${file}`) rej(`${err.code}: Failed to read ${file}`) return } return data })) }) this.blog.forEach((value, key) => { const regex = /# (.*)\nDate: (.*)\n---(.*?)---/s const match = value.match(regex) if (match) { const [, title, date, description] = match this.blog.set(key, { title: title, date: new Date(date), short: description, body: md.render(value) }) } else { this.blog.set(key, { title: undefined, date: undefined, short: undefined, body: md.render(value) }) } }) res(this.#OrderByDate(this.blog)) } }) } else { logger.Error('ERROR: blog directory does not exist') rej('ERROR: blog directory does not exist') } }) } #OrderByDate(x) { const entries =[] x.forEach((value, key) => {entries.push([key, value])}) entries.sort((a, b) => { const dateA = b[1].date const dateB = a[1].date return dateA - dateB }) return new Map(entries) } } module.exports = () => {return new Blog()}