Created
April 5, 2013 14:16
-
-
Save tomalex0/5319594 to your computer and use it in GitHub Desktop.
NodeJs Web Server
This file contains hidden or 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) { | |
| console.log('request starting...'); | |
| var filePath = '.' + request.url; | |
| if (filePath == './') | |
| filePath = './index.html'; | |
| var extname = path.extname(filePath); | |
| var contentType = 'text/html'; | |
| switch (extname) { | |
| case '.js': | |
| contentType = 'text/javascript'; | |
| break; | |
| case '.css': | |
| contentType = 'text/css'; | |
| 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(8000); | |
| console.log('Server running at http://127.0.0.1:8000/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment