James Ketrenos 1e24e5a934 Scanning and loading dirs
Signed-off-by: James Ketrenos <james_git@ketrenos.com>
2018-01-15 20:31:13 -08:00

56 lines
1.8 KiB
JavaScript
Executable File

"use strict";
const express = require("express"),
fs = require("fs"),
url = require("url"),
config = require("config");
const router = express.Router();
/* List of filename extensions we know are "potential" file extensions for
* assets we don"t want to return "index.html" for */
const extensions = [
"html", "js", "css", "eot", "gif", "ico", "jpeg", "jpg", "mp4",
"md", "ttf", "txt", "woff", "woff2", "yml", "svg"
];
/* Build the extension match RegExp from the list of extensions */
const extensionMatch = new RegExp("^.*?(" + extensions.join("|") + ")$", "i");
/* To handle dynamic routes, we return index.html to every request that
* gets this far -- so this needs to be the last route.
*
* However, that introduces site development problems when assets are
* referenced which don't yet exist (due to bugs, or sequence of adds) --
* the server would return HTML content instead of the 404.
*
* So, check to see if the requested path is for an asset with a recognized
* file extension.
*
* If so, 404 because the asset isn't there. otherwise assume it is a
* dynamic client side route and *then* return index.html.
*/
router.get("/*", function(req, res/*, next*/) {
const parts = url.parse(req.url),
basePath = req.app.get("basePath");
if (req.url == "/" || !extensionMatch.exec(parts.pathname)) {
/* Replace <script>'<base href="/BASEPATH/">';</script> in index.html with
* the basePath */
const index = fs.readFileSync("frontend/index.html", "utf8");
res.send(index.replace(
/<script>'<base href="BASEPATH">';<\/script>/,
"<base href='" + basePath + "'>"));
return;
}
console.log("Page not found: " + req.url);
return res.status(404).json({
message: "Page not found",
status: 404
});
});
module.exports = router;