Created
December 29, 2017 18:27
-
-
Save noampc/6a36885dbe75f24056ac7a3c7f50d2b7 to your computer and use it in GitHub Desktop.
Render entire EJS views directory with 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
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment