Created
May 2, 2011 07:07
-
-
Save pathsny/951251 to your computer and use it in GitHub Desktop.
request with caching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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