Created
March 9, 2012 07:19
-
-
Save markbrown4/2005435 to your computer and use it in GitHub Desktop.
A simple node server for serving front-end code
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 http = require('http'); | |
var fs = require('fs'); | |
var path = require('path'); | |
http.createServer(function (request, response) { | |
var filePath = '.' + request.url; | |
if (filePath == './') | |
filePath = './index.htm'; | |
var extname = path.extname(filePath); | |
var contentType = 'text/html'; | |
switch (extname) { | |
case '.js': | |
contentType = 'text/javascript'; | |
break; | |
case '.css': | |
contentType = 'text/css'; | |
break; | |
case '.jpg': | |
contentType = 'image'; | |
break; | |
case '.png': | |
contentType = 'image'; | |
break; | |
case '.json': | |
contentType = "application/json"; | |
break; | |
case '.manifest': | |
contentType = 'text/cache-manifest'; | |
break; | |
} | |
path.exists(filePath, function(exists) { | |
if (exists) { | |
fs.readFile(filePath, function(error, content) { | |
if (error) { | |
response.writeHead(500); | |
response.end(); | |
} | |
else { | |
response.writeHead(200, { 'Content-Type': contentType }); | |
response.end(content, 'utf-8'); | |
} | |
}); | |
} | |
else { | |
response.writeHead(404); | |
response.end(); | |
} | |
}); | |
}).listen(8125); | |
console.log('Server running at http://127.0.0.1:8125/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment