From 2b7c88596a2b787fa81f338e0620b9c90f0bffbe Mon Sep 17 00:00:00 2001 From: Trivernis Date: Tue, 9 Oct 2018 19:32:19 +0200 Subject: [PATCH] Code-Cleanup - Migrated to Webstorm and cleaned the code --- .gitignore | 1 + lib/caching.js | 135 ++++++++++++----------- lib/pp_html.js | 62 +++++------ lib/preprocessor.js | 95 ++++++++-------- lib/utils.js | 20 ++-- server.js | 260 ++++++++++++++++++++++---------------------- 6 files changed, 289 insertions(+), 284 deletions(-) diff --git a/.gitignore b/.gitignore index 2cc59e4..beed350 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ node_modules .log .cache package-lock.json +.idea diff --git a/lib/caching.js b/lib/caching.js index 62c32a2..b500c0d 100644 --- a/lib/caching.js +++ b/lib/caching.js @@ -1,39 +1,39 @@ const fs = require("fs"), - path = require("path"), - config_path = "./config/caching_dump.json", - cache_dump = JSON.parse(fs.readFileSync(config_path)), - cache_dir = "./.cache", - cache = {}; -var logger = require("winston"); + path = require("path"), + config_path = "./config/caching_dump.json", + cache_dump = JSON.parse(fs.readFileSync(config_path)), + cache_dir = "./.cache"; +let cache = {}; +let logger = require("winston"); if (cache_dump != null && cache_dump["last"] != null) cache = cache_dump["last"]; // read the data from the file dump /** * Sets the logger for logging - * @param {Winston Logger} newLogger + * @param {Object} newLogger */ -exports.setLogger = function(newLogger) { - logger = newLogger; -} +exports.setLogger = function (newLogger) { + logger = newLogger; +}; /** * Returns the data from files that were cached * @param {String} filename The name of the file that has been cached * @return {String} The data stored in the file */ -exports.getCached = function(filename) { - let cf = cache[filename]; - 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) { - cf.data = fs.readFileSync(cf.path); // store the file's data into the json - } else if (call_passed > 3600) { - 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.last_call = Date.now(); // set the last call to now - cf.call_count += 1; // increase the call count - if (cf.data != null) return cf.data; - logger.debug("Returning cached data for %s : %s", filename, cf.path); - return fs.readFileSync(cf.path); // return either the data or read the file +exports.getCached = function (filename) { + let cf = cache[filename]; + 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) { + cf.data = fs.readFileSync(cf.path); // store the file's data into the json + } else if (call_passed > 3600) { + 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.last_call = Date.now(); // set the last call to now + cf.call_count += 1; // increase the call count + if (cf.data != null) return cf.data; + logger.debug("Returning cached data for %s : %s", filename, cf.path); + 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} data The data form the file */ -exports.cache = function(filename, data) { - logger.verbose("Creating cache entry for %s", filename); - 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 count = 0; - 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 - logger.debug("Creating file %s", cache_path); - fs.writeFile(cache_path, data, (error) => { - logger.debug("Created file cache entry for %s", filename); - cache[filename] = { // create a cache-entry with the file's path when the file is written (so it won't be accessed before) - "path": cache_path, // the last call to the file, the count of calls and an - "last_call": null, // empty data field to store the file's data if the file - "call_count": 0, // was called often - "data": null, - "creation_time": Date.now(), - "changed": false - }; - fs.watch(filename, (eventType) => { // watch the file for changes - 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 +exports.cache = function (filename, data) { + logger.verbose("Creating cache entry for %s", filename); + 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 count = 0; + 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 + logger.debug("Creating file %s", cache_path); + fs.writeFile(cache_path, data, (err) => { + if (err !== null) logger.error(err); + else { + logger.debug("Created file cache entry for %s", filename); + cache[filename] = { // create a cache-entry with the file's path when the file is written (so it won't be accessed before) + "path": cache_path, // the last call to the file, the count of calls and an + "last_call": null, // empty data field to store the file's data if the file + "call_count": 0, // was called often + "data": null, + "creation_time": Date.now(), + "changed": false + } + } + fs.watch(filename, (eventType) => { // watch the file for changes + 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 * @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) { - let cached_entry = cache[filename]; - if (cached_entry) { // check if the cache entry exists - 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.path) { // check if the path variable is set - logger.debug("Found path entry for %s", filename) - return fs.existsSync(cached_entry.path); // return if the file exists +exports.isCached = function (filename) { + let cached_entry = cache[filename]; + if (cached_entry) { // check if the cache entry exists + 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.path) { // check if the path variable is set + logger.debug("Found path entry for %s", filename) + return fs.existsSync(cached_entry.path); // return if the file exists + } } - } - logger.debug("Found no cache entry for %s", filename); - return false; // return false if the cache entry doesn't exist + logger.debug("Found no cache entry for %s", filename); + 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. */ -exports.cleanup = function() { - logger.verbose("Dumping cache into cache_dump file"); - 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 -} +exports.cleanup = function () { + logger.verbose("Dumping cache into cache_dump file"); + 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 +}; diff --git a/lib/pp_html.js b/lib/pp_html.js index 6f98b07..c4697b4 100644 --- a/lib/pp_html.js +++ b/lib/pp_html.js @@ -2,12 +2,10 @@ * Preprocesses html-files */ const fs = require("fs"), - { - JSDOM - } = require('jsdom') + { JSDOM } = require('jsdom'), // ressources - 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 + 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 /** * Creates a css DOM element with href as source @@ -16,11 +14,11 @@ const fs = require("fs"), * @return {Object} the Link Element */ function createLinkElement(document, href) { - let link = document.createElement('link'); - link.setAttribute("rel", "stylesheet"); - link.setAttribute("type", "text/css"); - link.setAttribute("href", href); - return link; + let link = document.createElement('link'); + link.setAttribute("rel", "stylesheet"); + link.setAttribute("type", "text/css"); + link.setAttribute("href", href); + return link; } /** @@ -30,30 +28,30 @@ function createLinkElement(document, href) { * @return {Object} the Script Element */ function createScriptLinkElement(document, src) { - let script = document.createElement("script"); - script.setAttribute("type", "text/javascript"); - script.setAttribute("src", src); - return script; + let script = document.createElement("script"); + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", src); + return script; } /** * 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) { - var htmlstring = fs.readFileSync(filename); - try { - let dom = new JSDOM(htmlstring); // creates a dom from the html string - let document = dom.window.document; - let head = document.getElementsByTagName('head')[0]; // gets the documents 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, "/glob/jquery.js")); // prepend the JQuery 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 - } catch (error) { - console.error(error); - return htmlstring; - } -} +exports.formatHtml = function (filename) { + let htmlstring = fs.readFileSync(filename); + try { + let dom = new JSDOM(htmlstring); // creates a dom from the html string + let document = dom.window.document; + let head = document.getElementsByTagName('head')[0]; // gets the documents 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, "/glob/jquery.js")); // prepend the JQuery 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 + } catch (error) { + console.error(error); + return htmlstring; + } +}; diff --git a/lib/preprocessor.js b/lib/preprocessor.js index 541c01b..e6d0b03 100644 --- a/lib/preprocessor.js +++ b/lib/preprocessor.js @@ -1,59 +1,66 @@ const fs = require("fs"), - utils = require("./utils"), - caching = require("./caching"), + utils = require("./utils"), + caching = require("./caching"), // pp (preprocessors) - pp_html = require("./pp_html"), - pp_sass = require("node-sass"), + pp_html = require("./pp_html"), + pp_sass = require("node-sass"), - pp_config = { - ".sass" : "sass", - ".html": "html", - ".htm": "hmtl" - }; -var logger = require("winston"); + pp_config = { + ".sass": "sass", + ".html": "html", + ".htm": "hmtl" + }; +let logger = require("winston"); /** * Sets the logger for logging - * @param {Winston Logger} newLogger + * @param {Object} newLogger */ -exports.setLogger = function(newLogger) { - logger = newLogger; - caching.setLogger(logger); -} +exports.setLogger = function (newLogger) { + logger = newLogger; + caching.setLogger(logger); +}; /** * 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 * @return {String} The data that should be send */ -exports.getProcessed = function(filename) { - try { - logger.debug("Processing File %s", filename); - var extension = utils.getExtension(filename); // use the utils function to get the files extension - var data = null; - if (caching.isCached(filename)) return caching.getCached(filename) // return the cached file if it exists - logger.debug("File is not cached. Processing..."); - switch (pp_config[extension]) { - case "sass": - logger.debug("Processing sass %s", filename); - data = Buffer.from(pp_sass.renderSync({ // use the sass preprocessor - file: filename - }).css).toString("utf-8"); - break; - case "html": - logger.debug("Processing html %s", filename); - data = pp_html.formatHtml(filename); // use the html-preprocessor - break; - default: - logger.debug("No processor found for %s. Returning data.", filename); - return fs.readFileSync(filename); // just read the data from the file +exports.getProcessed = function (filename) { + try { + logger.debug("Processing File %s", filename); + let extension = utils.getExtension(filename); // use the utils function to get the files extension + let data = null; + if (caching.isCached(filename)) return caching.getCached(filename) // return the cached file if it exists + logger.debug("File is not cached. Processing..."); + switch (pp_config[extension]) { + case "sass": + logger.debug("Processing sass %s", filename); + data = Buffer.from(pp_sass.renderSync({ // use the sass preprocessor + file: filename + }).css).toString("utf-8"); + break; + case "html": + logger.debug("Processing html %s", filename); + data = pp_html.formatHtml(filename); // use the html-preprocessor + break; + default: + logger.debug("No processor found for %s. Returning data.", filename); + 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) { - logger.error(error); - return "Processing Error"; - } -} +}; + +/** + * Cleanup function that calls the cleanup for the caching module + */ +exports.cleanup = function() { + caching.cleanup(); +}; \ No newline at end of file diff --git a/lib/utils.js b/lib/utils.js index e2ebcbb..d478594 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -7,14 +7,14 @@ * @param {String} filename The name of the file. * @return {String} A string that represents the file-extension. */ -exports.getExtension = function(filename) { - if (!filename) return null; - try { - let exts = filename.match(/\.[a-z]+/g); // get the extension by using regex - if (exts) return exts[exts.length - 1]; // return the found extension - else return null; // return null if no extension could be found - } catch (error) { - logger.warn(error); - return null; - } +exports.getExtension = function (filename) { + if (!filename) return null; + try { + let exts = filename.match(/\.[a-z]+/g); // get the extension by using regex + if (exts) return exts[exts.length - 1]; // return the found extension + else return null; // return null if no extension could be found + } catch (error) { + console.error(error); + return null; + } } diff --git a/server.js b/server.js index 7b6ece6..62fa419 100644 --- a/server.js +++ b/server.js @@ -1,81 +1,81 @@ // requirement const https = require('https'), - fs = require('fs'), - urlparse = require('url'), - perfy = require('perfy'), - winston = require('winston'), - DailyRotateFile = require('winston-daily-rotate-file'), - path = require('path'), + fs = require('fs'), + urlparse = require('url'), + perfy = require('perfy'), + winston = require('winston'), + DailyRotateFile = require('winston-daily-rotate-file'), + path = require('path'), // own modules - utils = require("./lib/utils"), - prepro = require("./lib/preprocessor"), + utils = require("./lib/utils"), + prepro = require("./lib/preprocessor"), // args - args = require('args-parser')(process.argv), // create an args parser + args = require('args-parser')(process.argv), // create an args parser // config file - config = JSON.parse(fs.readFileSync("./config/server.json")), + config = JSON.parse(fs.readFileSync("./config/server.json")), // logging config using winston - fileLoggingFormat = winston.format.printf(info => { - return `${info.timestamp} ${info.level.toUpperCase()}: ${JSON.stringify(info.message)}`; // the logging format for files - }), - consoleLoggingFormat = winston.format.printf(info => { - return `${info.timestamp} [${info.level}] ${JSON.stringify(info.message)}`; //the logging format for the console - }), - loggingFullFormat = winston.format.combine( - winston.format.splat(), - winston.format.timestamp({ - format: 'MM-DD HH:mm:ss.SSS' // don't include the year because the filename already tells + fileLoggingFormat = winston.format.printf(info => { + return `${info.timestamp} ${info.level.toUpperCase()}: ${JSON.stringify(info.message)}`; // the logging format for files + }), + consoleLoggingFormat = winston.format.printf(info => { + return `${info.timestamp} [${info.level}] ${JSON.stringify(info.message)}`; //the logging format for the console + }), + loggingFullFormat = winston.format.combine( + winston.format.splat(), + winston.format.timestamp({ + 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 - options = { - key: fs.readFileSync('.ssh/key.pem'), // the key-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" + options = { + key: fs.readFileSync('.ssh/key.pem'), // the key-file + cert: fs.readFileSync('.ssh/cert.pem') // the certificate-file }, - ".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 + 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": { + "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 --- @@ -84,62 +84,62 @@ const https = require('https'), * @return {boolean} Returns false if the server stopped by error. */ function main() { - try { - prepro.setLogger(logger); - https.createServer(options, function(req, res) { - logger.verbose({'msg': 'Received request', 'method': req.method, 'url': req.url}); + try { + prepro.setLogger(logger); + https.createServer(options, function (req, res) { + logger.verbose({'msg': 'Received request', 'method': req.method, 'url': req.url}); - perfy.start('response-calculation'); // caluclate the response time - let url = urlparse.parse(req.url); // parse the url - let uri = url.pathname; // set uri to the urls uriame - logger.debug({"msg": 'Got URL by using url package','url': url, 'path': uri}); + perfy.start('response-calculation'); // caluclate the response time + let url = urlparse.parse(req.url); // parse the url + let uri = url.pathname; // set uri to the urls uriame + 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 - logger.debug({'response-length': response.length, 'mime-type': mime}); + let [response, mime] = getResponse(uri); // get a response for the url path + logger.debug({'response-length': response.length, 'mime-type': mime}); - res.writeHead(200, {"Content-Type": mime || "text/plain"}); // write the mime as head - res.end(response); // write the response - 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 + res.writeHead(200, {"Content-Type": mime || "text/plain"}); // write the mime as head + res.end(response); // write the response + 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 - }).listen(port); // server listens on port specified in the parameter - } catch (error) { - logger.error(error); - logger.info("Shutting Down..."); - caching.cleanup(); - winston.end(); - return false; - } + }).listen(port); // server listens on port specified in the parameter + } catch (error) { + logger.error(error); + logger.info("Shutting Down..."); + prepro.cleanup(); + winston.end(); + return false; + } } /** * 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. - * @return {String} An Array containing (Either the files content or an error message) and the mime-type. + * @param uri + * @return {string[]} An Array containing (Either the files content or an error message) and the mime-type. */ 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 - logger.verbose({'msg':'calculating response', 'path': uri}); - let gp = prepro.getProcessed; - try { - // get the file extension - let extension = utils.getExtension(uri); - // 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")) { - logger.verbose("Using global uri"); - if (extension == ".sass") return [gp("." + uri), "text/css"]; - else return [gp("." + uri), "text/javascript"]; + 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}); + let gp = prepro.getProcessed; + try { + // get the file extension + let extension = utils.getExtension(uri); + // 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")) { + logger.verbose("Using global uri"); + if (extension === ".sass") return [gp("." + uri), "text/css"]; + 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 */ function getMount(uri) { - if (mounts){ // if mounts are set - for (var mount of mounts){ // for each set mount - 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 - if (uri.match(regEx)) { // if there is a match - return uri.replace(regEx, mount.path); // returnthe modified uri + if (mounts) { // if mounts are set + 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 + let regEx = RegExp(mount.mount); // create a regex from the mount + if (uri.match(regEx)) { // if there is a match + return uri.replace(regEx, mount.path); // returnthe modified uri + } + } } - } } - } - return false; + return false; } // Executing the main function -if (typeof require != 'undefined' && require.main == module) { - logger.exceptions.handle( - new winston.transports.File({ - filename: './.log/frontserver-exceptions.log' - }) - ); - logger.info("Starting up... "); // log the current date so that the logfile is better to read. - main(); +if (typeof require !== 'undefined' && require.main === module) { + logger.exceptions.handle( + new winston.transports.File({ + filename: './.log/frontserver-exceptions.log' + }) + ); + logger.info("Starting up... "); // log the current date so that the logfile is better to read. + main(); }