Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Last active December 17, 2015 08:49
Show Gist options
  • Save nemtsov/5582362 to your computer and use it in GitHub Desktop.
Save nemtsov/5582362 to your computer and use it in GitHub Desktop.
The quickest dependency-less working static-file server. It'll strem files for you.
var http = require('http')
, url = require('url')
, path = require('path')
, fs = require('fs')
, HTTP_PORT = (process.env.PORT || 3000)
, server;
server = http.createServer(function (req, res) {
var publicDir = path.join(__dirname, 'public');
serveStatic(publicDir, req, res);
});
server.listen(HTTP_PORT, function () {
console.log('Listening on http://localhost:%d', HTTP_PORT);
});
//----
function serveStatic(rootDir, req, res) {
var urlPath = decodeURI(url.parse(req.url).pathname)
getFileStream(rootDir, urlPath, function (err, file) {
if (err) return handleError(err, res);
res.writeHead(200, {'Content-Type': file.contentType});
file.stream.pipe(res);
});
}
function handleError(err, res) {
if (err.code === 'ENOENT') {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404 BaQa\'! (file not found)');
} else {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('500 Ghuy\'cha\'! (something broke)');
}
}
//----
function getFileStream(rootDir, urlPath, cb) {
var filepath = path.join(rootDir, urlPath)
fs.stat(filepath, function (err, stat) {
if (err) return cb(err);
if (stat.isDirectory()) return getFileStream(
rootDir, path.join(urlPath, 'index.html'), cb);
cb(null, {
contentType: getContentType(urlPath)
, stream: fs.createReadStream(filepath)
})
});
}
function getContentType(urlPath) {
return /\.html$/.test(urlPath) ? 'text/html' :
/\.js$/.test(urlPath) ? 'application/javascript' :
/\.css$/.test(urlPath) ? 'text/css' :
/\.ico$/.test(urlPath) ? 'image/x-icon' :
/\.png$/.test(urlPath) ? 'image/png' :
/\.jpeg$/.test(urlPath) ? 'image/jpeg' :
/\.gif$/.test(urlPath) ? 'image/gif' :
'text/html';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment