summaryrefslogtreecommitdiff
path: root/source/blog.js
blob: 57735b75242523032ad0a13d7d79e2e2b0607701 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const fs = require('fs')
const path = require('path')
const markdownit = require('markdown-it')
const md = markdownit()
const logger = require('./logger')()

// Parse markdown
class Blog {
    constructor() {}

    async ReadBlogs() {return this.#LoadBlogs().then(output => {return output})}

    async #LoadBlogs() {
        return new Promise((res, rej) => {
            fs.readdir('./blog/', (err, files) => {
                if (err) {
                    logger.Error(`Error reading directory ${err}`)
                    rej(false)
                }

                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)
                            return
                        }
                        return data
                    }))
                })
                this.blog.forEach((value, key) => {
                    this.regex = /# (.*)\nDate: (.*)\n---(.*?)---/s
                    this.match = value.match(this.regex)

                    if (this.match) {
                        const [, title, date, description] = this.match
                        this.object = {
                            title: title,
                            date: new Date(date),
                            short: description,
                            body: md.render(value)
                        }
                        this.blog.set(key, this.object)
                    } else {
                        this.blog.set(key, {
                            title: undefined,
                            date: undefined,
                            short: undefined,
                            body: md.render(value)
                        })
                    }
                })
                res(this.blog)
            })
        })
    }
}

module.exports = () => {return new Blog()}