Created
August 17, 2011 20:51
-
-
Save coverslide/1152585 to your computer and use it in GitHub Desktop.
A simple no-dependency script I use for serving static files. Very useful for viewing html docs.
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
#!/usr/bin/env node | |
var http = require('http') | |
, path = require('path') | |
, url = require('url') | |
, fs = require('fs') | |
, base = path.resolve(process.argv[2] || '.') | |
, port = process.argv[3] || 8080 | |
http.createServer(function (req, res) { | |
var requrl = url.parse(req.url).pathname | |
, pathname = path.join(base,requrl) | |
fs.stat(pathname, function(err, stat){ | |
if(err){ | |
error(err, res) | |
} | |
else if(stat.isDirectory()){ | |
fs.readdir(pathname, function(err, dir){ | |
var index = dir.indexOf('index.html') !== -1 | |
if(err){ | |
error(err, res) | |
} | |
else if(index){ | |
res.statusCode = 302 | |
res.setHeader('Location',path.join(requrl, 'index.html')) | |
res.end() | |
// servefile(res, path.join(requrl, 'index.html')) | |
} | |
else{ | |
dir.forEach(function(file){ | |
res.write('<div><a href="' + path.join(requrl, file) + '">' + file + '</a></div>') | |
}) | |
res.end() | |
} | |
}) | |
} | |
else{ | |
servefile(res, pathname) | |
} | |
}) | |
}).listen(port); | |
function error(err, res){ | |
res.status = 404 | |
res.end('<h4>404</h4><p>' + err.message + '</p><pre>' + err.stack + '</pre>') | |
return | |
} | |
function servefile(res, pathname){ | |
var ext = path.extname(pathname) | |
res.setHeader('Content-type', extlookup(ext)) | |
try{ | |
var stream = fs.createReadStream(pathname) | |
} | |
catch(err){ | |
error(err, res) | |
return | |
} | |
stream.pipe(res) | |
stream.on('end', function(){ | |
}) | |
} | |
var mime_lookup = { | |
'.html': 'text/html' | |
, '.json': 'text/json' | |
, '.xml': 'text/xml' | |
, '.js': 'text/javascript' | |
, '.css': 'text/css' | |
, '.gif': 'image/gif' | |
, '.jpg': 'image/jpeg' | |
, '.jpeg': 'image/jpeg' | |
, '.png': 'image/png' | |
} | |
function extlookup(ext){ | |
if(ext in mime_lookup){ | |
return mime_lookup[ext] | |
} | |
return 'text/plain' | |
} | |
console.log(path.resolve(base) + " served on port " + port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment