Skip to content

Instantly share code, notes, and snippets.

@aahnik
Last active March 4, 2024 14:12
Show Gist options
  • Save aahnik/3ddbc3daf72890c4566498138cd14797 to your computer and use it in GitHub Desktop.
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"
/*
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