Skip to content

Instantly share code, notes, and snippets.

@kkleidal
Forked from ryanflorence/static_server.js
Last active August 29, 2015 14:10
Show Gist options
  • Save kkleidal/0274e732d7c11e6372e7 to your computer and use it in GitHub Desktop.
Save kkleidal/0274e732d7c11e6372e7 to your computer and use it in GitHub Desktop.
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
function wrapHTML(html) {
return "<!DOCTYPE html><html><body>" + html + "</body></html>\n";
}
function serveIndex(response, rootPath, localPath, cb) {
fs.readdir(path.join(rootPath, localPath), function(err, files) {
if (err) {
serveError(response, 500, "Could not read directory contents.");
return;
}
list = "<ul>";
for (var i = 0; i < files.length; ++i) {
list += "<li><a href='" + path.join(localPath, files[i]) + "'>" + files[i] + "</a></li>";
}
list += "</ul>";
serveSuccess(response, "<h1>" + localPath + "</h1>" + list);
});
}
function serveSuccess(response, body) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(wrapHTML(body));
response.end();
}
function serveError(response, code, message) {
response.writeHead(code, {"Content-Type": "text/html"});
response.write(wrapHTML("<h1>" + code + ": " + message + "</h1>\n"));
response.end();
}
function getURI(request) {
return decodeURIComponent(url.parse(request.url, true).path.replace(/\+/g, ' '))
}
function getRequestHandler(rootPath) {
return function handleRequest(request, response) {
var uri = getURI(request)
, filename = path.join(rootPath, uri);
fs.exists(filename, function(exists) {
if(!exists) {
serveError(response, 404, "Not found");
return;
}
if (fs.statSync(filename).isDirectory()) {
serveIndex(response, rootPath, uri, function() {});
return;
}
var readStream = fs.createReadStream(filename);
response.writeHead(200);
readStream.pipe(response);
});
};
}
function main() {
if (process.argv.length != 4 && process.argv.length != 3) {
console.error("Usage: PORT [PATH]");
return;
}
port = 8888;
try {
port = parseInt(process.argv[2], 10);
} catch (e) {
console.error("Usage: PORT [PATH]. Could not parse port.");
return;
}
rootPath = process.cwd();
if (process.argv.length == 4) {
rootPath = process.argv[3];
}
http.createServer(getRequestHandler(rootPath)).listen(port);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment