My ham website
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.4 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. 'use strict'
  2. const express = require('express')
  3. const fs = require('fs')
  4. const path = require('path')
  5. const app = express()
  6. app.use(express.static('public'))
  7. app.set('view engine', 'ejs')
  8. app.get('/', (req, res) => {
  9. res.render('pages/index', {
  10. title: "Levi Olson",
  11. active: "home",
  12. content: ""
  13. })
  14. })
  15. // This is really really inefficient... this should be cached and built during a build.
  16. app.get('/posts', (req, res) => {
  17. const postDir = __dirname + '/posts'
  18. let files = fs.readdirSync(postDir, 'utf8')
  19. let data = {
  20. title: "Posts - Levi Olson",
  21. active: "posts",
  22. posts: []
  23. }
  24. for (let i = 0; i < files.length; i++) {
  25. if (path.extname(files[i]) === '.json') {
  26. let postData = getData(files[i])
  27. if (postData) {
  28. data.posts.push(postData)
  29. } else {
  30. console.log(files[i], 'does not have a corresponding "html" file')
  31. }
  32. }
  33. }
  34. data.posts.sort(function (a, b) {
  35. var keyA = new Date(a.created_at),
  36. keyB = new Date(b.created_at)
  37. // Compare the 2 dates
  38. if (keyA < keyB) return 1
  39. if (keyA > keyB) return -1
  40. return 0
  41. })
  42. res.render('pages/posts', data)
  43. })
  44. function getData(file) {
  45. let postData
  46. try {
  47. postData = JSON.parse(fs.readFileSync('./posts/' + file, 'utf8'))
  48. postData.content = fs.readFileSync('./posts/' + postData.content_file, 'utf8')
  49. } catch (e) {
  50. return
  51. }
  52. return postData
  53. }
  54. app.get('/about', (req, res) => {
  55. res.sendFile(__dirname + '/views/pages/about.html')
  56. })
  57. app.get('/uncopyright', (req, res) => {
  58. return res.sendFile(__dirname + '/views/pages/uncopyright.html')
  59. })
  60. app.get('/404', (req, res) => {
  61. return res.status(404).render('pages/404', {
  62. title: "Page Not Found - Levi Olson",
  63. active: ""
  64. })
  65. })
  66. app.get('/core.css', (req, res) => {
  67. res.sendFile(__dirname + '/core.css')
  68. })
  69. app.get('/posts/:post', (req, res) => {
  70. let post = req.params.post
  71. let postData
  72. try {
  73. postData = JSON.parse(fs.readFileSync('./posts/' + post + '.json', 'utf8'))
  74. postData.content = fs.readFileSync('./posts/' + postData.content_file, 'utf8')
  75. } catch (e) {
  76. return res.redirect('/404')
  77. }
  78. return res.render('pages/post', postData)
  79. })
  80. const port = 3000
  81. app.listen(port, () => console.log('Example app listening on port ' + port + '!'))
  82. module.exports = app