Last active
March 4, 2024 14:12
-
-
Save aahnik/3ddbc3daf72890c4566498138cd14797 to your computer and use it in GitHub Desktop.
[Ejs + Static Files] Frotend Server process... Server all ejs templates from a directory "views" + server static files from "public"
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
/* | |
frontend server | |
server HTML,CSS and frontend js | |
use ejs to render html | |
Credits: https://gist.github.com/noampc/6a36885dbe75f24056ac7a3c7f50d2b7 | |
*/ | |
import express from "express"; | |
import fs from "fs"; | |
const server = express(); | |
server.set("view engine", "ejs"); | |
function filesToRender(dir) { | |
function fileSubstring(file, dir) { | |
return file.substring(0, file.length - 4).replace(dir, ""); | |
} | |
function readDirRecursive(dir, filelist) { | |
let files = fs.readdirSync(dir); | |
filelist = filelist || []; | |
files.map((file) => { | |
if (fs.statSync(dir + "/" + file).isDirectory()) { | |
filelist = readDirRecursive(dir + "/" + file, filelist); | |
} else { | |
filelist.push(dir + "/" + file); | |
} | |
}); | |
return filelist; | |
} | |
return readDirRecursive(dir).map((file) => { | |
return fileSubstring(file, dir); | |
}); | |
} | |
function renderFile(file) { | |
server.get(file, (req, res) => { | |
res.render(file.slice(1)); | |
}); | |
if (file.slice(-5) === "index") { | |
server.get(file.substring(0, file.length - 5), (req, res) => { | |
res.render(file.slice(1)); | |
}); | |
} | |
} | |
filesToRender("views").map((file) => renderFile(file)); | |
server.use(express.static("public")); | |
server.listen(3001, () => { | |
console.log(`Serving ejs from ${3001}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment