Code-Cleanup

- Migrated to Webstorm and cleaned the code
pull/4/head
Trivernis 6 years ago
parent cf9f51013c
commit 2b7c88596a

1
.gitignore vendored

@ -31,3 +31,4 @@ node_modules
.log .log
.cache .cache
package-lock.json package-lock.json
.idea

@ -1,39 +1,39 @@
const fs = require("fs"), const fs = require("fs"),
path = require("path"), path = require("path"),
config_path = "./config/caching_dump.json", config_path = "./config/caching_dump.json",
cache_dump = JSON.parse(fs.readFileSync(config_path)), cache_dump = JSON.parse(fs.readFileSync(config_path)),
cache_dir = "./.cache", cache_dir = "./.cache";
cache = {}; let cache = {};
var logger = require("winston"); let logger = require("winston");
if (cache_dump != null && cache_dump["last"] != null) cache = cache_dump["last"]; // read the data from the file dump if (cache_dump != null && cache_dump["last"] != null) cache = cache_dump["last"]; // read the data from the file dump
/** /**
* Sets the logger for logging * Sets the logger for logging
* @param {Winston Logger} newLogger * @param {Object} newLogger
*/ */
exports.setLogger = function(newLogger) { exports.setLogger = function (newLogger) {
logger = newLogger; logger = newLogger;
} };
/** /**
* Returns the data from files that were cached * Returns the data from files that were cached
* @param {String} filename The name of the file that has been cached * @param {String} filename The name of the file that has been cached
* @return {String} The data stored in the file * @return {String} The data stored in the file
*/ */
exports.getCached = function(filename) { exports.getCached = function (filename) {
let cf = cache[filename]; let cf = cache[filename];
let call_passed = (Date.now()-cf.last_call) / 1000; // calculate the time since the last call of the file let call_passed = (Date.now() - cf.last_call) / 1000; // calculate the time since the last call of the file
if (cf.call_count > 10 && call_passed < 60) { if (cf.call_count > 10 && call_passed < 60) {
cf.data = fs.readFileSync(cf.path); // store the file's data into the json cf.data = fs.readFileSync(cf.path); // store the file's data into the json
} else if (call_passed > 3600) { } else if (call_passed > 3600) {
cf.call_count = 0; // reset the counter when an hour has passed since the last call cf.call_count = 0; // reset the counter when an hour has passed since the last call
cf.data = null; // reset the data to free memory cf.data = null; // reset the data to free memory
} }
cf.last_call = Date.now(); // set the last call to now cf.last_call = Date.now(); // set the last call to now
cf.call_count += 1; // increase the call count cf.call_count += 1; // increase the call count
if (cf.data != null) return cf.data; if (cf.data != null) return cf.data;
logger.debug("Returning cached data for %s : %s", filename, cf.path); logger.debug("Returning cached data for %s : %s", filename, cf.path);
return fs.readFileSync(cf.path); // return either the data or read the file return fs.readFileSync(cf.path); // return either the data or read the file
}; };
/** /**
@ -41,59 +41,58 @@ exports.getCached = function(filename) {
* @param {String} filename The name of the file * @param {String} filename The name of the file
* @param {String} data The data form the file * @param {String} data The data form the file
*/ */
exports.cache = function(filename, data) { exports.cache = function (filename, data) {
logger.verbose("Creating cache entry for %s", filename); logger.verbose("Creating cache entry for %s", filename);
if (!fs.existsSync("./.cache")) fs.mkdirSync("./.cache"); // if the cache folder doesn't exist, create it if (!fs.existsSync("./.cache")) fs.mkdirSync("./.cache"); // if the cache folder doesn't exist, create it
let cache_fn = filename.replace(/[^\w\.]/g, "__"); // remove invalid path characters let cache_fn = filename.replace(/[^\w.]/g, "__"); // remove invalid path characters
let count = 0; let count = 0;
while (fs.existsSync(filename + count + ".cache")) count++; // check if a file with the same name already exists and increase count while (fs.existsSync(filename + count + ".cache")) count++; // check if a file with the same name already exists and increase count
let cache_path = path.join(cache_dir, cache_fn+count+".cache"); // create the final file path. Cachedir + cached filename (without invalid) + count + .cache let cache_path = path.join(cache_dir, cache_fn + count + ".cache"); // create the final file path. Cachedir + cached filename (without invalid) + count + .cache
logger.debug("Creating file %s", cache_path); logger.debug("Creating file %s", cache_path);
fs.writeFile(cache_path, data, (error) => { fs.writeFile(cache_path, data, (err) => {
logger.debug("Created file cache entry for %s", filename); if (err !== null) logger.error(err);
cache[filename] = { // create a cache-entry with the file's path when the file is written (so it won't be accessed before) else {
"path": cache_path, // the last call to the file, the count of calls and an logger.debug("Created file cache entry for %s", filename);
"last_call": null, // empty data field to store the file's data if the file cache[filename] = { // create a cache-entry with the file's path when the file is written (so it won't be accessed before)
"call_count": 0, // was called often "path": cache_path, // the last call to the file, the count of calls and an
"data": null, "last_call": null, // empty data field to store the file's data if the file
"creation_time": Date.now(), "call_count": 0, // was called often
"changed": false "data": null,
}; "creation_time": Date.now(),
fs.watch(filename, (eventType) => { // watch the file for changes "changed": false
logger.debug("Change detected on %s", filename); }
if (eventType == 'change') cache[filename].changed = true; // if the event change is detected set the change attribute to true }
}); fs.watch(filename, (eventType) => { // watch the file for changes
}); // write the data asynchronously to the file logger.debug("Change detected on %s", filename);
if (eventType === 'change') cache[filename].changed = true; // if the event change is detected set the change attribute to true
});
}); // write the data asynchronously to the file
}; };
/** /**
* Returns if the file is already cached * Returns if the file is already cached. It returns false if changes were detected in the file
* @param {String} filename The filename to check * @param {String} filename The filename to check
* @return {Boolean} Is it cached or not * @return {Boolean} Is it cached or not
* TODO: Use last access or use creation_time property to check if the file might
* be too old. If the function returns false, a new cache-file will be created which
* has a different name from the old. On each startup a function could check if
* there are cache-files that are not listet in the cache_dump and delete them.
*/ */
exports.isCached = function(filename) { exports.isCached = function (filename) {
let cached_entry = cache[filename]; let cached_entry = cache[filename];
if (cached_entry) { // check if the cache entry exists if (cached_entry) { // check if the cache entry exists
logger.debug("Found cache entry for %s", filename); logger.debug("Found cache entry for %s", filename);
if (cached_entry.changed) return false; // if a change was detected recache the file if (cached_entry.changed) return false; // if a change was detected recache the file
if (cached_entry.path) { // check if the path variable is set if (cached_entry.path) { // check if the path variable is set
logger.debug("Found path entry for %s", filename) logger.debug("Found path entry for %s", filename)
return fs.existsSync(cached_entry.path); // return if the file exists return fs.existsSync(cached_entry.path); // return if the file exists
}
} }
} logger.debug("Found no cache entry for %s", filename);
logger.debug("Found no cache entry for %s", filename); return false; // return false if the cache entry doesn't exist
return false; // return false if the cache entry doesn't exist
} }
/** /**
* A function that dumps the config into the config file after appending the cache to it. * A function that dumps the config into the config file after appending the cache to it.
*/ */
exports.cleanup = function() { exports.cleanup = function () {
logger.verbose("Dumping cache into cache_dump file"); logger.verbose("Dumping cache into cache_dump file");
cache_dump["last"] = cache; // append the cache to the dump object cache_dump["last"] = cache; // append the cache to the dump object
fs.writeFileSync(config_path, JSON.stringify(cache_dump)); // write the dump data to the file fs.writeFileSync(config_path, JSON.stringify(cache_dump)); // write the dump data to the file
} };

@ -2,12 +2,10 @@
* Preprocesses html-files * Preprocesses html-files
*/ */
const fs = require("fs"), const fs = require("fs"),
{ { JSDOM } = require('jsdom'),
JSDOM
} = require('jsdom')
// ressources // ressources
defaultCss = "/glob/style.sass", // the default style that is embedded in every html defaultCss = "/glob/style.sass", // the default style that is embedded in every html
defaultJs = "/glob/script.js"; // the default script that is embedded in every html defaultJs = "/glob/script.js"; // the default script that is embedded in every html
/** /**
* Creates a css DOM element with href as source * Creates a css DOM element with href as source
@ -16,11 +14,11 @@ const fs = require("fs"),
* @return {Object} the Link Element * @return {Object} the Link Element
*/ */
function createLinkElement(document, href) { function createLinkElement(document, href) {
let link = document.createElement('link'); let link = document.createElement('link');
link.setAttribute("rel", "stylesheet"); link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css"); link.setAttribute("type", "text/css");
link.setAttribute("href", href); link.setAttribute("href", href);
return link; return link;
} }
/** /**
@ -30,30 +28,30 @@ function createLinkElement(document, href) {
* @return {Object} the Script Element * @return {Object} the Script Element
*/ */
function createScriptLinkElement(document, src) { function createScriptLinkElement(document, src) {
let script = document.createElement("script"); let script = document.createElement("script");
script.setAttribute("type", "text/javascript"); script.setAttribute("type", "text/javascript");
script.setAttribute("src", src); script.setAttribute("src", src);
return script; return script;
} }
/** /**
* Formats the html string by adding a link to the standard css and to the standard javascript file. * Formats the html string by adding a link to the standard css and to the standard javascript file.
* @param {String} htmlstring A string read from an html file or a html document string itself. * @return {String} A html-string that represents a document.
* @return {String} A html-string that represents a document. * @param filename
*/ */
exports.formatHtml = function(filename) { exports.formatHtml = function (filename) {
var htmlstring = fs.readFileSync(filename); let htmlstring = fs.readFileSync(filename);
try { try {
let dom = new JSDOM(htmlstring); // creates a dom from the html string let dom = new JSDOM(htmlstring); // creates a dom from the html string
let document = dom.window.document; let document = dom.window.document;
let head = document.getElementsByTagName('head')[0]; // gets the documents head let head = document.getElementsByTagName('head')[0]; // gets the documents head
head.prepend(createLinkElement(document, defaultCss)); // prepend the default css to the head head.prepend(createLinkElement(document, defaultCss)); // prepend the default css to the head
head.prepend(createScriptLinkElement(document, defaultJs)); // prepend the default script to the head head.prepend(createScriptLinkElement(document, defaultJs)); // prepend the default script to the head
head.prepend(createScriptLinkElement(document, "/glob/jquery.js")); // prepend the JQuery to the head head.prepend(createScriptLinkElement(document, "/glob/jquery.js")); // prepend the JQuery to the head
head.prepend(createScriptLinkElement(document, "/glob/vue.js")); // prepend the Vue to the head head.prepend(createScriptLinkElement(document, "/glob/vue.js")); // prepend the Vue to the head
return dom.serialize(); // return a string of the document return dom.serialize(); // return a string of the document
} catch (error) { } catch (error) {
console.error(error); console.error(error);
return htmlstring; return htmlstring;
} }
} };

@ -1,59 +1,66 @@
const fs = require("fs"), const fs = require("fs"),
utils = require("./utils"), utils = require("./utils"),
caching = require("./caching"), caching = require("./caching"),
// pp (preprocessors) // pp (preprocessors)
pp_html = require("./pp_html"), pp_html = require("./pp_html"),
pp_sass = require("node-sass"), pp_sass = require("node-sass"),
pp_config = { pp_config = {
".sass" : "sass", ".sass": "sass",
".html": "html", ".html": "html",
".htm": "hmtl" ".htm": "hmtl"
}; };
var logger = require("winston"); let logger = require("winston");
/** /**
* Sets the logger for logging * Sets the logger for logging
* @param {Winston Logger} newLogger * @param {Object} newLogger
*/ */
exports.setLogger = function(newLogger) { exports.setLogger = function (newLogger) {
logger = newLogger; logger = newLogger;
caching.setLogger(logger); caching.setLogger(logger);
} };
/** /**
* Returns the data for the file. In some cases the data is processed or loaded from cache. * Returns the data for the file. In some cases the data is processed or loaded from cache.
* @param {String} filename The file containing the data * @param {String} filename The file containing the data
* @return {String} The data that should be send * @return {String} The data that should be send
*/ */
exports.getProcessed = function(filename) { exports.getProcessed = function (filename) {
try { try {
logger.debug("Processing File %s", filename); logger.debug("Processing File %s", filename);
var extension = utils.getExtension(filename); // use the utils function to get the files extension let extension = utils.getExtension(filename); // use the utils function to get the files extension
var data = null; let data = null;
if (caching.isCached(filename)) return caching.getCached(filename) // return the cached file if it exists if (caching.isCached(filename)) return caching.getCached(filename) // return the cached file if it exists
logger.debug("File is not cached. Processing..."); logger.debug("File is not cached. Processing...");
switch (pp_config[extension]) { switch (pp_config[extension]) {
case "sass": case "sass":
logger.debug("Processing sass %s", filename); logger.debug("Processing sass %s", filename);
data = Buffer.from(pp_sass.renderSync({ // use the sass preprocessor data = Buffer.from(pp_sass.renderSync({ // use the sass preprocessor
file: filename file: filename
}).css).toString("utf-8"); }).css).toString("utf-8");
break; break;
case "html": case "html":
logger.debug("Processing html %s", filename); logger.debug("Processing html %s", filename);
data = pp_html.formatHtml(filename); // use the html-preprocessor data = pp_html.formatHtml(filename); // use the html-preprocessor
break; break;
default: default:
logger.debug("No processor found for %s. Returning data.", filename); logger.debug("No processor found for %s. Returning data.", filename);
return fs.readFileSync(filename); // just read the data from the file return fs.readFileSync(filename); // just read the data from the file
}
caching.cache(filename, data); // cache the file for faster access next time
logger.debug("Cached file %s", filename);
return data; // return the data
} catch (error) {
logger.error(error);
return "Processing Error";
} }
caching.cache(filename, data); // cache the file for faster access next time };
logger.debug("Cached file %s", filename);
return data; // return the data /**
} catch (error) { * Cleanup function that calls the cleanup for the caching module
logger.error(error); */
return "Processing Error"; exports.cleanup = function() {
} caching.cleanup();
} };

@ -7,14 +7,14 @@
* @param {String} filename The name of the file. * @param {String} filename The name of the file.
* @return {String} A string that represents the file-extension. * @return {String} A string that represents the file-extension.
*/ */
exports.getExtension = function(filename) { exports.getExtension = function (filename) {
if (!filename) return null; if (!filename) return null;
try { try {
let exts = filename.match(/\.[a-z]+/g); // get the extension by using regex let exts = filename.match(/\.[a-z]+/g); // get the extension by using regex
if (exts) return exts[exts.length - 1]; // return the found extension if (exts) return exts[exts.length - 1]; // return the found extension
else return null; // return null if no extension could be found else return null; // return null if no extension could be found
} catch (error) { } catch (error) {
logger.warn(error); console.error(error);
return null; return null;
} }
} }

@ -1,81 +1,81 @@
// requirement // requirement
const https = require('https'), const https = require('https'),
fs = require('fs'), fs = require('fs'),
urlparse = require('url'), urlparse = require('url'),
perfy = require('perfy'), perfy = require('perfy'),
winston = require('winston'), winston = require('winston'),
DailyRotateFile = require('winston-daily-rotate-file'), DailyRotateFile = require('winston-daily-rotate-file'),
path = require('path'), path = require('path'),
// own modules // own modules
utils = require("./lib/utils"), utils = require("./lib/utils"),
prepro = require("./lib/preprocessor"), prepro = require("./lib/preprocessor"),
// args // args
args = require('args-parser')(process.argv), // create an args parser args = require('args-parser')(process.argv), // create an args parser
// config file // config file
config = JSON.parse(fs.readFileSync("./config/server.json")), config = JSON.parse(fs.readFileSync("./config/server.json")),
// logging config using winston // logging config using winston
fileLoggingFormat = winston.format.printf(info => { fileLoggingFormat = winston.format.printf(info => {
return `${info.timestamp} ${info.level.toUpperCase()}: ${JSON.stringify(info.message)}`; // the logging format for files return `${info.timestamp} ${info.level.toUpperCase()}: ${JSON.stringify(info.message)}`; // the logging format for files
}), }),
consoleLoggingFormat = winston.format.printf(info => { consoleLoggingFormat = winston.format.printf(info => {
return `${info.timestamp} [${info.level}] ${JSON.stringify(info.message)}`; //the logging format for the console return `${info.timestamp} [${info.level}] ${JSON.stringify(info.message)}`; //the logging format for the console
}), }),
loggingFullFormat = winston.format.combine( loggingFullFormat = winston.format.combine(
winston.format.splat(), winston.format.splat(),
winston.format.timestamp({ winston.format.timestamp({
format: 'MM-DD HH:mm:ss.SSS' // don't include the year because the filename already tells format: 'MM-DD HH:mm:ss.SSS' // don't include the year because the filename already tells
}),
fileLoggingFormat // the logging format for files that logs with a capitalized level
),
logger = winston.createLogger({
level: winston.config.npm.levels, // logs with npm levels
format: loggingFullFormat, // the full format for files
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(), // colorizes the console logging output
winston.format.splat(),
winston.format.timestamp({
format: 'YY-MM-DD HH:mm:ss.SSS' // logs with the year to the console
}),
consoleLoggingFormat // logs with the custom console format
),
level: args.loglevel || 'info' // logs to the console with the arg loglevel or info if it is not given
}),
new winston.transports.File({
level: 'debug', // logs with debug level to the active file
filename: './.log/rcn-frontserver.log', // the filename of the current file,
options: {flags: 'w'} // overwrites the file on restart
}),
new DailyRotateFile({
level: 'verbose', // log verbose in the rotating logvile
filename: './.log/frontserver-%DATE%.log', // the pattern of the filename
datePattern: 'YYYY-MM-DD', // the pattern of %DATE%
zippedArchive: true, // indicates that old logfiles should get zipped
maxSize: '32m', // the maximum filesize
maxFiles: '30d' // the maximum files to keep
})
]
}), }),
fileLoggingFormat // the logging format for files that logs with a capitalized level
),
logger = winston.createLogger({
level: winston.config.npm.levels, // logs with npm levels
format: loggingFullFormat, // the full format for files
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(), // colorizes the console logging output
winston.format.splat(),
winston.format.timestamp({
format: 'YY-MM-DD HH:mm:ss.SSS' // logs with the year to the console
}),
consoleLoggingFormat // logs with the custom console format
),
level: args.loglevel || 'info' // logs to the console with the arg loglevel or info if it is not given
}),
new winston.transports.File({
level: 'debug', // logs with debug level to the active file
filename: './.log/rcn-frontserver.log', // the filename of the current file,
options: {flags: 'w'} // overwrites the file on restart
}),
new DailyRotateFile({
level: 'verbose', // log verbose in the rotating logvile
filename: './.log/frontserver-%DATE%.log', // the pattern of the filename
datePattern: 'YYYY-MM-DD', // the pattern of %DATE%
zippedArchive: true, // indicates that old logfiles should get zipped
maxSize: '32m', // the maximum filesize
maxFiles: '30d' // the maximum files to keep
})
]
}),
// serveroptions // serveroptions
options = { options = {
key: fs.readFileSync('.ssh/key.pem'), // the key-file key: fs.readFileSync('.ssh/key.pem'), // the key-file
cert: fs.readFileSync('.ssh/cert.pem') // the certificate-file cert: fs.readFileSync('.ssh/cert.pem') // the certificate-file
},
port = args.port || 443, // the port the server is running on. It's the https standard
routes = config.routes || {
".html": {
"path": "./res/html", // standard route to the html files
"mime": "text/html"
}, },
".js": { port = args.port || 443, // the port the server is running on. It's the https standard
"path": "./res/scripts", // standard route to the script files routes = config.routes || {
"mime": "text/javascript" ".html": {
} "path": "./res/html", // standard route to the html files
}, "mime": "text/html"
mounts = config.mounts, // mounts are more important than routes. },
cache = {}; // cache stores filenames for cached processed files ".js": {
"path": "./res/scripts", // standard route to the script files
"mime": "text/javascript"
}
},
mounts = config.mounts, // mounts are more important than routes.
cache = {}; // cache stores filenames for cached processed files
// --- functional declaration part --- // --- functional declaration part ---
@ -84,62 +84,62 @@ const https = require('https'),
* @return {boolean} Returns false if the server stopped by error. * @return {boolean} Returns false if the server stopped by error.
*/ */
function main() { function main() {
try { try {
prepro.setLogger(logger); prepro.setLogger(logger);
https.createServer(options, function(req, res) { https.createServer(options, function (req, res) {
logger.verbose({'msg': 'Received request', 'method': req.method, 'url': req.url}); logger.verbose({'msg': 'Received request', 'method': req.method, 'url': req.url});
perfy.start('response-calculation'); // caluclate the response time perfy.start('response-calculation'); // caluclate the response time
let url = urlparse.parse(req.url); // parse the url let url = urlparse.parse(req.url); // parse the url
let uri = url.pathname; // set uri to the urls uriame let uri = url.pathname; // set uri to the urls uriame
logger.debug({"msg": 'Got URL by using url package','url': url, 'path': uri}); logger.debug({"msg": 'Got URL by using url package', 'url': url, 'path': uri});
let [response, mime] = getResponse(uri); // get a response for the url path let [response, mime] = getResponse(uri); // get a response for the url path
logger.debug({'response-length': response.length, 'mime-type': mime}); logger.debug({'response-length': response.length, 'mime-type': mime});
res.writeHead(200, {"Content-Type": mime || "text/plain"}); // write the mime as head res.writeHead(200, {"Content-Type": mime || "text/plain"}); // write the mime as head
res.end(response); // write the response res.end(response); // write the response
let execTime = perfy.end('response-calculation').fullMilliseconds; // get the execution time let execTime = perfy.end('response-calculation').fullMilliseconds; // get the execution time
logger.debug("Response-Time: " + execTime + " ms for " + req.url, "debug"); // log the execution time logger.debug("Response-Time: " + execTime + " ms for " + req.url, "debug"); // log the execution time
}).listen(port); // server listens on port specified in the parameter }).listen(port); // server listens on port specified in the parameter
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
logger.info("Shutting Down..."); logger.info("Shutting Down...");
caching.cleanup(); prepro.cleanup();
winston.end(); winston.end();
return false; return false;
} }
} }
/** /**
* Returns a string that depends on the uri It gets the data from the routes variable. * Returns a string that depends on the uri It gets the data from the routes variable.
* @param {String} uriNormally a file-name. Depending on the extension, an other root-uriis choosen. * @param uri
* @return {String} An Array containing (Either the files content or an error message) and the mime-type. * @return {string[]} An Array containing (Either the files content or an error message) and the mime-type.
*/ */
function getResponse(uri) { function getResponse(uri) {
if (!uri || uri == "/") uri = "/index.html"; // uri redirects to the index.html if it is not set or if it is root if (!uri || uri === "/") uri = "/index.html"; // uri redirects to the index.html if it is not set or if it is root
logger.verbose({'msg':'calculating response', 'path': uri}); logger.verbose({'msg': 'calculating response', 'path': uri});
let gp = prepro.getProcessed; let gp = prepro.getProcessed;
try { try {
// get the file extension // get the file extension
let extension = utils.getExtension(uri); let extension = utils.getExtension(uri);
// returns the global script or css if the extension is css or js and the root-uriis glob. // returns the global script or css if the extension is css or js and the root-uriis glob.
if (uri.includes("/glob") && (extension == ".sass" || extension == ".js")) { if (uri.includes("/glob") && (extension === ".sass" || extension === ".js")) {
logger.verbose("Using global uri"); logger.verbose("Using global uri");
if (extension == ".sass") return [gp("." + uri), "text/css"]; if (extension === ".sass") return [gp("." + uri), "text/css"];
else return [gp("." + uri), "text/javascript"]; else return [gp("." + uri), "text/javascript"];
}
let mount = getMount(uri); // get mount for uri it will be uses as path later instead of route
logger.verbose("Mount for uri is " + mount);
let route = routes[extension]; // get the route from the extension json
logger.verbose("Found route: " + JSON.stringify(route));
if (!route) return ["Not Allowed", "text/plain"]; // return not allowed if no route was found
return [gp(mount || path.join(route["path"], uri)), route["mime"]]; // get processed output (done by preprocessor)
} catch (error) {
logger.error(error);
return ["Error", "text/plain"];
} }
let mount = getMount(uri); // get mount for uri it will be uses as path later instead of route
logger.verbose("Mount for uri is "+ mount);
let route = routes[extension]; // get the route from the extension json
logger.verbose("Found route: "+JSON.stringify(route));
if (!route) return ["Not Allowed", "text/plain"]; // return not allowed if no route was found
return [gp(mount || path.join(route["path"],uri)), route["mime"]]; // get processed output (done by preprocessor)
} catch (error) {
logger.error(error);
return ["Error", "text/plain"];
}
} }
/** /**
@ -148,26 +148,26 @@ function getResponse(uri) {
* @return {String} The uri that points to the mounted path * @return {String} The uri that points to the mounted path
*/ */
function getMount(uri) { function getMount(uri) {
if (mounts){ // if mounts are set if (mounts) { // if mounts are set
for (var mount of mounts){ // for each set mount for (let mount of mounts) { // for each set mount
if (mount.mount && mount.path) { // if the mount has the mount parameter and the path parameter if (mount.mount && mount.path) { // if the mount has the mount parameter and the path parameter
let regEx = RegExp(mount.mount); // create a regex from the mount let regEx = RegExp(mount.mount); // create a regex from the mount
if (uri.match(regEx)) { // if there is a match if (uri.match(regEx)) { // if there is a match
return uri.replace(regEx, mount.path); // returnthe modified uri return uri.replace(regEx, mount.path); // returnthe modified uri
}
}
} }
}
} }
} return false;
return false;
} }
// Executing the main function // Executing the main function
if (typeof require != 'undefined' && require.main == module) { if (typeof require !== 'undefined' && require.main === module) {
logger.exceptions.handle( logger.exceptions.handle(
new winston.transports.File({ new winston.transports.File({
filename: './.log/frontserver-exceptions.log' filename: './.log/frontserver-exceptions.log'
}) })
); );
logger.info("Starting up... "); // log the current date so that the logfile is better to read. logger.info("Starting up... "); // log the current date so that the logfile is better to read.
main(); main();
} }

Loading…
Cancel
Save