Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 783
Jonathan Ong Avatar asked Dec 04 '25 22:12

Jonathan Ong


1 Answers

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.

like image 103
Vadim Baryshev Avatar answered Dec 07 '25 16:12

Vadim Baryshev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!