Created
March 18, 2019 21:29
-
-
Save jremi/3e0df146815929763417dfd55aec9b35 to your computer and use it in GitHub Desktop.
Super Simple Static HTML template loader for Express JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Add your html files inside the folder ./html | |
For example | |
-- index.html | |
-- about.html | |
When the Express server starts it auto loads all of the HTML template data, | |
and automatically creates GET routes using the name of each html file. | |
So using the example above you would automatically have the routes / and /about | |
created on Express startup. | |
*/ | |
const express = require('express') | |
const app = express() | |
const port = 3000 | |
const fs = require('fs') | |
const htmlFolderPath = `${__dirname}/html/` | |
const htmlFolderContents = fs.readdirSync(htmlFolderPath) | |
let html = {} | |
htmlFolderContents.forEach(file=>{ | |
let currentFile = file.split('.html'); | |
if(currentFile.length > 0){ | |
html[currentFile[0]] = fs.readFileSync(`${htmlFolderPath}${file}`, null).toString() | |
} | |
}) | |
const createRegularPageRoutes = (pageName) => { | |
let routeRoot = '/' | |
if( pageName === 'index' ) routeName = routeRoot | |
else routeName = `${routeRoot}${pageName}` | |
app.get(routeName, (req, res) => { | |
res.send(html[pageName]) | |
}) | |
} | |
for(let page in html){ | |
createRegularPageRoutes(page) | |
} | |
app.listen(port, () => console.log(`Example app listening on port ${port}!`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment