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.

98 lines
2.5 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. console.log(new Date(a.created_at_short), new Date(b.created_at_short));
  36. var keyA = new Date(a.created_at_short),
  37. keyB = new Date(b.created_at_short)
  38. // Compare the 2 dates
  39. if (keyA < keyB) return 1
  40. if (keyA > keyB) return -1
  41. return 0
  42. })
  43. res.render('pages/posts', data)
  44. })
  45. function getData(file) {
  46. let postData
  47. try {
  48. postData = JSON.parse(fs.readFileSync('./posts/' + file, 'utf8'))
  49. postData.content = fs.readFileSync('./posts/' + postData.content_file, 'utf8')
  50. } catch (e) {
  51. return
  52. }
  53. return postData
  54. }
  55. app.get('/about', (req, res) => {
  56. res.sendFile(__dirname + '/views/pages/about.html')
  57. })
  58. app.get('/uncopyright', (req, res) => {
  59. return res.sendFile(__dirname + '/views/pages/uncopyright.html')
  60. })
  61. app.get('/404', (req, res) => {
  62. return res.status(404).render('pages/404', {
  63. title: "Page Not Found - Levi Olson",
  64. active: ""
  65. })
  66. })
  67. app.get('/core.css', (req, res) => {
  68. res.sendFile(__dirname + '/core.css')
  69. })
  70. app.get('/posts/:post', (req, res) => {
  71. let post = req.params.post
  72. let postData
  73. try {
  74. postData = JSON.parse(fs.readFileSync('./posts/' + post + '.json', 'utf8'))
  75. postData.content = fs.readFileSync('./posts/' + postData.content_file, 'utf8')
  76. } catch (e) {
  77. return res.redirect('/404')
  78. }
  79. return res.render('pages/post', postData)
  80. })
  81. const port = 3000
  82. app.listen(port, () => console.log('Example app listening on port ' + port + '!'))
  83. module.exports = app