Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js page caching

Node.js page caching

Problem

Is there a simple way to Cache pages in Express, preferably Memcached? I'm using Jade as a templating system. I'm looking to cache certain pages for visitors for about 30 seconds. Preferably it uses express.render, but I'm open to suggestions. Thanks!

Problem courtesy of: Jonathan Ong

Solution

You need to handle result of rendering.

var cache = {};

var getPageFromCache(url, callback) {
    if (cache[url]) {
        // Get page from cache
        callback(undefined, cache[url]);
    } else {
        // Get nothing
        callback();
    }
};

var setPageToCache(url, content) {
    // Save to cache
    cache[url] = content;
};

app.get('/', function(req, res){
    getPageFromCache(req.url, function(err, content) {
        if (err) return req.next(err);
        if (content) {
            res.send(content);
        } else {
            res.render('index.jade', { title: 'My Site' }, function(err, content) {
                // Render handler
                if (err) return req.next(err);
                setPageToCache(req.url, page);
                res.send(content);
            });
        }
    });
});

Implement getPageFromCache and setPageToCache to work with memcached if you need.

Solution courtesy of: Vadim Baryshev

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js page caching

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×