Node.js page caching
2 answers
You need to process the rendering result.
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.
+8
source to share
I am using a simple package: cacher , this is an explicit middleware page caching supported by memcached.
Usage example:
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
+4
source to share