Subscribe via RSS Feed

Implement Caching Server with Express.js custom middleware

May 8, 2015 0 Comments

In this article, we explored the capability of expressjs custom middleware. nike air max 90 pas cher We have made a minimal cache server implementation in expressjs middleware, which will serve as cache for GET web requests. fjallraven kanken soldes So below is the main server code implementation with inline documentation. Server.js

 var express = require('express'); var app = express(); var cache = require('./cacheServer'); // the Cache Server middleware var cached = []; // Array where the cache to be saved in memory var pathname = ''; var url = require('url'); var cacheHelper = require('./cacheHelper'); // cache method utility app.use(cache(cached)); // injection of the middleware app.get('/', function (req, res) { cacheHelper.setCache(req, res,cached,"Hello World"); // serving request and save in cache res.send('Hello World!'); }); app.get('/about', function (req, res) { cacheHelper.setCache(req, res,cached,"Hello about"); // serving request and save in cache res.send('Hello about!'); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Application is running at http://%s:%s', host, port); })

Below is main implementation of cache server. Lunettes de soleil Ray Ban Here the the request is first checked within the cache array object. nike air max 2017 pas cher If this cache content is found, it will be served from cache, otherwise the request will be forwarded to main request serving process for the server. cacheServer.js

 var cacheHelper = require('./cacheHelper.js'); // the middleware function module.exports = function(cached) { return function(req, res, next) { var resource = cacheHelper.getCache(req, res,cached); // get the content from cache if(req.method == 'GET') // cache is implemented only for 'GET' method { if (typeof resource !== 'undefined') { res.end(resource); // serve from cache } else { next(); // forward to fresh request processing } } else { next(); // forward to fresh request processing } } }; 

Below is a helper class for get object from cache and set object to cache. new balance homme 574 pas cher cacheHelper.js

 var url = require('url'); var pathname = ''; function getCache(req,res,cached) { pathname = url.parse(req.url).pathname; return cached[pathname]; } function setCache(req,res,cached,content) { pathname = url.parse(req.url).pathname; cached[pathname] = 'cached response' + ' from '+ pathname + ' ' + content; } exports.getCache = getCache; exports.setCache = setCache; 

We expect reader to be habituated with node.js and express.js coding.

Leave a Reply

You must be logged in to post a comment.