Skip to content

Instantly share code, notes, and snippets.

@boazsender
Created November 18, 2011 17:02
Show Gist options
  • Save boazsender/1377050 to your computer and use it in GitHub Desktop.
Save boazsender/1377050 to your computer and use it in GitHub Desktop.
Simple Node Webserver
/*
This is a slightly tweaked version of
https://github.com/nhira/node-simple-webserver/blob/master/webserver.js
*/
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs");
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd() + "", uri);
filename = filename.replace(/%20/g, " ");
sys.log('[' + request.connection.remoteAddress + '][' + request.url + '] mapped to [' + filename + ']');
path.exists(filename, function(exists) {
if (!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
sys.log(filename + ' could not be found');
return;
}
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.end();
sys.log(err);
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(80);
sys.puts("Server running at http://localhost");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment