Created
November 12, 2012 17:30
-
-
Save uiur/4060694 to your computer and use it in GitHub Desktop.
画像のurl入れたらキャッシュしてくれるやつ
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
/** | |
* Module dependencies. | |
*/ | |
var express = require('express') | |
, http = require('http') | |
, path = require('path') | |
, crypto = require('crypto') | |
, fs = require('fs'); | |
var app = express(); | |
var IMAGES_DIR = 'images/'; | |
app.configure(function(){ | |
app.set('port', process.env.PORT || 3000); | |
app.use(express.favicon()); | |
app.use(express.logger('dev')); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
}); | |
app.configure('development', function(){ | |
app.use(express.errorHandler()); | |
}); | |
// GET /?url=http://hoge.com/hoge.png | |
app.get('/', function (req, res) { | |
var image_url = req.query.url | |
, extension = '.' + image_url.split('.').pop(); | |
if (!image_url.match(/\.(jpg|jpeg|gif|png)$/)) { | |
res.send(400, 'Bad Request: url must have extension (.jpg, .jpeg, .gif, .png)'); | |
return; | |
} | |
var sha1 = crypto.createHash('sha1'); | |
sha1.update(image_url, 'ascii'); | |
var filename = sha1.digest('hex') + extension; | |
res.sendfile(IMAGES_DIR + filename, function (err) { | |
if (!err) { | |
return; | |
} | |
http.get(image_url, function (res_from_external) { | |
if (res_from_external.statusCode !== 200) { | |
res.send(404); | |
return; | |
} | |
var ws = fs.createWriteStream(IMAGES_DIR + filename); | |
res_from_external.on('data', function (data) { | |
ws.write(data, 'binary'); | |
}) | |
.on('end', function () { | |
ws.end(); | |
res.sendfile(IMAGES_DIR + filename); | |
}); | |
}); | |
}); | |
}); | |
http.createServer(app).listen(app.get('port'), function(){ | |
console.log("Express server listening on port " + app.get('port')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
express使うほどじゃなかった