BlogSharer/index.js
Bingus_Violet f55552fbf9 CSS!
2023-12-28 17:48:56 -06:00

81 lines
No EOL
2.1 KiB
JavaScript

const express = require("express"),
chokidar = require("chokidar"),
fs = require("fs"),
path = require("path"),
showdown = require("showdown"),
mkthtml = new showdown.Converter()
mkthtml.setFlavor("github")
const PORT = process.env.PORT || 8080
var dataPath = path.join(__dirname, 'data')
var postsPath = path.join(dataPath, 'posts')
var staticPath = path.join(__dirname, 'static')
var watcher = chokidar.watch(postsPath)
var app = express()
app.use(express.static(staticPath))
var reqPaths = [dataPath, postsPath]
for (var i = 0; i < reqPaths.length; i++) {
var p = reqPaths[i]
if (!fs.existsSync(p)) {
fs.mkdirSync(p)
}
}
app.listen(PORT, () => {
console.log("Violet's Limbo is now listening on: " + PORT)
})
function pageUpdate() {
var postsArray = fs.readdirSync(postsPath)
var posts = {}
for (let index = 0; index < postsArray.length; index++) {
const item = postsArray[index];
const absPath = path.join(postsPath, item)
const birthtime = fs.statSync(absPath).birthtime
posts[birthtime] = {"post": item.substring(0, item.length - 3), "date": birthtime}
}
var html = ""
postsArray = Object.keys(posts).sort().reverse()
for (var i = 0; i < postsArray.length; i++) {
var addedHTML = ""
var post = posts[postsArray[i]]
addedHTML += `<h2><a href="./post/${post.post}">${post.post}</h2></a>`
html += addedHTML
}
var html = fs.readFileSync(path.join(__dirname, 'resources/mainPage.html')).toString().replace('{POSTS}', html)
fs.writeFileSync(path.join(staticPath, 'index.html'), html)
}
watcher
.on('add', pageUpdate)
.on('change', pageUpdate)
.on('unlink', pageUpdate)
app.get('/post/:post*', (req, res) => {
var post = fs.readFileSync(path.join(postsPath, req.params.post + '.md')).toString()
post = mkthtml.makeHtml(post)
var html = fs.readFileSync(path.join(__dirname, 'resources/postPage.html')).toString()
html = html.replace('{POST}', post)
html = html.replace('{POST_TITLE}', req.params.post)
res.send(html)
})