Skip to content

Instantly share code, notes, and snippets.

@rioki
Created September 13, 2012 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rioki/3714400 to your computer and use it in GitHub Desktop.
Save rioki/3714400 to your computer and use it in GitHub Desktop.
A HTTP server serving static files in note.js.
var fs = require("fs");
var path = require("path");
var url = require("url");
var mime = require("mime");
var http = require("http");
function start(htdocs, port) {
http.createServer(function (request, response) {
var file = url.parse(request.url).pathname;
var fullFile = path.join(htdocs, file);
if (fs.existsSync(fullFile) && fs.statSync(fullFile).isDirectory()) {
fullFile = path.join(fullFile, "index.html");
}
fs.readFile(fullFile, function (err, data) {
if (err) {
console.log("serving 404 " + file);
response.writeHead(404, {"Content-Type": "text/html"});
var body = "<html>" +
"<head><title>404 File Not Found</title></head>" +
"<body>" +
"<h1>404 File Not Found</h1>" +
"<p>" + err + "</p>" +
"</body>" +
"</html>";
response.write(body);
response.end();
}
else {
var m = mime.lookup(fullFile);
console.log("serving 200 " + file + " (" + m + ")");
response.writeHead(200, {"Content-Type": m});
response.end(data);
}
});
}).listen(port);
console.log("started server on port " + port);
}
exports.start = start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment