Created
September 3, 2013 18:38
-
-
Save paceaux/6427841 to your computer and use it in GitHub Desktop.
Nodejs webserver in under 40 lines
This file contains hidden or 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 http = require("http"), | |
url = require("url"), | |
path = require("path"), | |
fs = require("fs"), | |
port = 8891, | |
types = { | |
'html' : 'text/html', | |
'htm' : 'text/html', | |
'js' : 'application/javascript', | |
'css' : 'text/css' | |
}; | |
http.createServer(function (request, response) { | |
serveFiles(request, response); | |
}).listen(port); | |
function serveFiles(request, response) { | |
var uri = url.parse(request.url).pathname, dir = __dirname, filename = path.join(dir, '/', uri); | |
fs.exists(filename, function (exists){ | |
if (!exists) { | |
response.writeHead(404, {'Content-Type' : 'text/html'}); | |
response.write("<!DOCTYPE html><html>"); | |
response.write("<head><title>404: Page not found</title></head><body>"); | |
fs.readdir(dir, function (err, files) { | |
response.write("<ul>"); | |
for (i=0; i<files.length; i++){ | |
var file = files[i]; | |
file = '<li><a href="'+file.toString() + '">'+file.toString()+'</li>'; | |
response.write(file); | |
} | |
response.write("</ul>"); | |
}); | |
response.write("</body></html>") | |
} else { | |
var type = filename.split('.'); | |
type = type[type.length - 1]; | |
response.writeHead(200, {'Content-Type' : types[type] + '; charset=utf-8'}); | |
fs.createReadStream(filename).pipe(response); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment