Last active
January 3, 2016 03:29
-
-
Save nazomikan/8402951 to your computer and use it in GitHub Desktop.
expire-test
This file contains 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
var http = require('http') | |
, connect = require('connect') | |
, app | |
; | |
app = connect() | |
.use(assetsExpire(1000 * 60 * 3)) | |
.use(connect.static('public')) | |
.use(function(req, res){ | |
res.end(' \ | |
<html> \ | |
<head> \ | |
<script type="text/javascript" src="/hoge.js"></script> \ | |
</head> \ | |
<body>hello world</body> \ | |
</html> \ | |
'); | |
}); | |
http.createServer(app).listen(3000); | |
/** | |
* 静的ファイル(js, css)のキャッシュ(expireの)設定 | |
* | |
* @param {Number} expire expireの有効期間(単位ms) | |
* @return {Function} middleware | |
*/ | |
function assetsExpire(expire) { | |
var url = require('url') | |
, path = require('path') | |
; | |
// set default value | |
expire = expire == null ? (1000 * 60 * 30) : expire; | |
return function (req, res, next) { | |
var pathname = url.parse(req.url).pathname | |
, ext | |
, now | |
; | |
// 拡張子取得 | |
ext = path.extname(pathname); | |
if (!ext) { | |
return next(); | |
} | |
switch(ext) { | |
case '.js': | |
case '.css': | |
now = (new Date(Date.now() + expire)).toUTCString(); | |
res.setHeader('Expires', now); | |
res.setHeader('Cache-Control', "max-age=" + (expire / 1000)); | |
default: | |
next(); | |
} | |
}; | |
} |
This file contains 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
// public/hoge.js | |
console.log("hello world"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment