From 5e79857e9a8231b2a890eeff54fe8e012c16890f Mon Sep 17 00:00:00 2001 From: Gabriel Csapo Date: Fri, 11 Aug 2017 00:15:08 -0700 Subject: [PATCH] static server caching - adds caching to static-server --- CHANGELOG.md | 1 + lib/helpers/static-server.js | 13 ++++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 735ce33..1c27fba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Unreleased +- adds caching to static-server - abstract models into their own files and their own collections - fixes the middleware request logger - fixes CLI responses diff --git a/lib/helpers/static-server.js b/lib/helpers/static-server.js index 0d3242c..8a9650b 100644 --- a/lib/helpers/static-server.js +++ b/lib/helpers/static-server.js @@ -20,6 +20,8 @@ const map = { '.doc': 'application/msword' }; +const cache = {}; + http.createServer((req, res) => { let { url } = req; @@ -30,6 +32,11 @@ http.createServer((req, res) => { const parsedUrl = Url.parse(url); let pathname = `.${parsedUrl.pathname}`; + if(cache[pathname]) { + res.setHeader('Content-Type', cache[pathname]['Content-Type']); + return res.end(cache[pathname]['data']); + } + const ext = path.parse(pathname).ext; fs.exists(pathname, (exist) => { @@ -46,8 +53,12 @@ http.createServer((req, res) => { res.statusCode = 500; res.end(`Error getting the file: ${err}.`); } else { + cache[pathname] = { + 'Content-Type': map[ext] || 'text/plain', + data + }; // if the file is found, set Content-type and send data - res.setHeader('Content-type', map[ext] || 'text/plain'); + res.setHeader('Content-Type', map[ext] || 'text/plain'); res.end(data); } });