Created
December 26, 2010 23:23
-
-
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.
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 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