Last active
August 29, 2015 14:08
-
-
Save djphoenix/0a18cc0b17d067358e8f to your computer and use it in GitHub Desktop.
Node.JS static files host
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 mime = require('mime'), fs = require('fs'), url = require('url'), zlib = require('zlib'); | |
module.exports = function(req, res){ | |
var fn = url.parse(req.url).pathname; | |
if (fn.substr(-1) == '/') fn += 'index.html'; | |
var file = __dirname + '/static' + fn; | |
try { | |
var ct = mime.lookup(file); | |
if (ct.split('/')[0] == 'text') ct += '; charset=UTF-8'; | |
var stat = fs.statSync(file), | |
gzip = (('accept-encoding' in req.headers) && (req.headers['accept-encoding'].split(',').map(function(e){return e.trim();}).indexOf('gzip') != -1)), | |
h = { | |
"Content-Type":ct, | |
"Connection": "keep-alive", | |
"Cache-Control": "max-age=31536000; must-revalidate", | |
"Last-Modified": stat['mtime'].toUTCString() | |
}; | |
if (gzip) h['Content-Encoding'] = 'gzip'; | |
if ('if-modified-since' in req.headers) { | |
var cd = new Date(req.headers['if-modified-since']); | |
if (stat['mtime'].toUTCString() == cd.toUTCString()) { | |
res.writeHead(304,h); | |
res.end(); | |
return; | |
} | |
} | |
res.writeHead(200,h); | |
var f = fs.createReadStream(file); | |
if (gzip) { | |
var gz = zlib.createGzip({level:3}); | |
f.pipe(gz).pipe(res); | |
} else f.pipe(res); | |
} catch(e) { | |
res.writeHead(404,{ | |
"Content-Type":"text/html; charset=UTF-8", | |
"Connection": "keep-alive", | |
}); | |
res.end('404 not found'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment