Skip to content

Instantly share code, notes, and snippets.

@davejlong
Created December 26, 2010 23:23
Show Gist options
  • Save davejlong/755721 to your computer and use it in GitHub Desktop.
Save davejlong/755721 to your computer and use it in GitHub Desktop.
An Improved Node.js server with default index.htm document and global 404 and 500 error handlers.
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs");
//Create the server wrapper
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
console.log('URI: ' + uri);
if (uri.match(/\/$/)) uri = uri + 'index.htm';
if (uri == '/server.js') throw404();
var filename = path.join(process.cwd(), uri);
console.log('File Name: ' + filename)
// Check if the file exists
path.exists(filename, function(exists){
// If it doesn't exist
if (!exists) throw404();
fs.readFile(filename, "binary", function(err, file){
if (err) throw500();
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
function throw404(){
response.writeHead(404, {
"Content-Type": "text/plain"
});
response.write("404 Not Found\n");
response.end();
return;
}
function throw500(){
response.writeHead(500, {
"Content-Type": "text/plain"
});
response.write("500 Not Found\n");
response.end();
return;
}
}).listen(8000);
sys.puts("Server running at http://localhost:8000/");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment