Jonathan Ong
Jonathan Ong

Reputation: 20315

Node.js page caching

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!

Upvotes: 3

Views: 4248

Answers (2)

Giovanni Cappellotto
Giovanni Cappellotto

Reputation: 4855

I'm using a simple package: cacher, it's an express middleware handling page caching backed by memcached.

Example usage:

var Cacher = require("cacher")
var cacher = new Cacher("myhost:11211")

// as a global middleware
app.use(cacher.cacheHourly())
// or per route
app.get("/long-cache", cacher.cacheDaily(), ...)
app.get("/short-cache", cacher.cacheOneMinute(), ...)
app.get("/no-cache", ...)

// listen for events
cacher.on("hit", function(url) {
  console.log("woohoo!", url)
})

cacher.on("miss", function(url) {
  console.log("doh!", url)
})

cacher.on("error", function(err) {
  console.log(err)
})

See also the project on GitHub

Upvotes: 4

Vadim Baryshev
Vadim Baryshev

Reputation: 26189

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.

Upvotes: 8

Related Questions