Skip to content

Instantly share code, notes, and snippets.

@munro
Created August 24, 2011 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munro/1166992 to your computer and use it in GitHub Desktop.
Save munro/1166992 to your computer and use it in GitHub Desktop.
Kitten Cache
var fs = require('fs'),
http = require('http'),
path = require('path');
var CACHE_DIR = '.kitten_cache';
if (!path.existsSync(CACHE_DIR)) {
fs.mkdirSync('.kitten_cache', 0755);
} else if (!fs.statSync(CACHE_DIR).isDirectory()) {
console.error('Cache dir `%s` must be a directory.', CACHE_DIR)
process.exit(1);
}
http.createServer(function (req, res) {
var match = req.url.match(/^\/(\d+)\/(\d+)\/?$/), filename, cache_in;
if (!match) {
res.writeHead(404);
res.end('404 Image not found\r\n');
return;
}
// Try to read from cache
filename = '.kitten_cache/' + match[1] + '_' + match[2];
cache_in = fs.createReadStream(filename);
cache_in.pipe(res, {end: false});
cache_in.on('end', function () {
res.end();
console.log('From cache ' + req.url);
});
// Otherwise pull from web
cache_in.on('error', function (e) {
var cache_out, img_req;
cache_out = fs.createWriteStream(filename, {mode: 0644});
cache_out.on('error', function (e) {
console.log('Could not write to cache: ' + e.message);
});
img_req = http.get({
host: 'placekitten.com',
port: 80,
path: req.url
});
img_req.on('all', function () {
console.log('all', arguments);
});
img_req.on('response', function (img_res) {
console.log('From web ' + req.url);
img_res.pipe(res);
if (cache_out.writable) {
img_res.pipe(cache_out);
}
});
img_req.on('close', function () {
console.log('From web ' + req.url);
});
img_req.on('error', function (e) {
res.writeHead(500);
res.end('500 could not fetch image from placekitten.com: ' +
e.message);
console.log('Failed web ' + req.url);
});
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment