Created
September 13, 2012 13:46
-
-
Save rioki/3714400 to your computer and use it in GitHub Desktop.
A HTTP server serving static files in note.js.
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 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