Skip to content

Instantly share code, notes, and snippets.

@pathsny
Created May 2, 2011 07:07
Show Gist options
  • Select an option

  • Save pathsny/951251 to your computer and use it in GitHub Desktop.

Select an option

Save pathsny/951251 to your computer and use it in GitHub Desktop.
request with caching
request: function(options, cb) {
var cache;
if (options.cache) cache = './data/cache/' + options.cache;
var http_req = function() {
req(options, function(error, response, body){
if (!error && options.cache) {
if (response.headers['content-encoding'].search('gzip') != -1) {
// UHOH
}
console.log(body)
fs.writeFile(cache, body);
};
cb(error, response, body);
});
};
if (!cache) return http_req();
fs.stat(cache, function(err, stats){
console.log(stats)
if (!err && stats.mtime.between(Date.now().addWeeks(-1), Date.now())) {
fs.readFile(cache, function (err, data) {
if (err) http_req()
else {
var result = JSON.parse(data);
cb(undefined,result[0], result[1]);
}
});
} else {
return http_req();
}
});
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment