Created
October 29, 2011 19:02
-
-
Save tomlane/1324934 to your computer and use it in GitHub Desktop.
A Well commented http server written in node.
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
/* | |
A well commented http server written in node. | |
Written by: Tom Lane, http://github.com/tomlane | |
All Public Work by Tom Lane is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.0 UK: England & Wales License. | |
*/ | |
//calling the required http and fs modules | |
var http = require('http'); | |
var fs = require('fs'); | |
//create a new http server. | |
var httpserver = http.Server(); | |
//convert html files in to variables so that it will be easier to code later. | |
var index = fs.readFileSync("index.html"); | |
var about = fs.readFileSync("about.html"); | |
var contact = fs.readFileSync("contact.html"); | |
//function for every new request. | |
httpserver.on("request", function (request, response) { | |
//check the url | |
if (request.url === "/") { | |
//log the request. | |
console.log("recieved request for index.html"); | |
//open a response with code 200. | |
response.writeHead(200, {"Content-Type": "text/html"}); | |
//send the relevent file to client. | |
response.write(index); | |
//end the reponse. | |
response.end(); | |
} | |
else if (request.url === "/about") { | |
console.log("recieved request for about.html"); | |
response.writeHead(200, {"Content-Type": "text/html"}); | |
response.write(about); | |
response.end(); | |
} | |
else if (request.url === "/contact") { | |
console.log("recieved request for contact.html") | |
response.writeHead(200, {"Content-Type": "text/html"}); | |
response.write(contact); | |
response.end(); | |
} | |
//If the request is not available send a 404 warning to the console and 404 to the client. | |
else { | |
//log the 404 in the console along with the url being requested by the client. | |
console.warn("someone hit a 404! they were trying to access: " + request.url) | |
//send 404 to the client. this could also link to a custom 404 page. | |
response.writeHead(404); | |
//end the response. | |
response.end(); | |
} | |
}) | |
//server port. | |
httpserver.listen('8000'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment