Last active
December 14, 2015 03:59
-
-
Save ksafranski/5024668 to your computer and use it in GitHub Desktop.
Simple Node HTTP Server with logging
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'), | |
| fs = require('fs'), | |
| path = require('path'), | |
| port = 8080, | |
| default_file = 'index.html'; | |
| http.createServer(function (request, response) { | |
| // Params | |
| var contentType, | |
| reqURL = request.url.split('?'), | |
| file = reqURL[0], | |
| query = reqURL[1], | |
| filePath = '.' + file, | |
| cTypes = { | |
| ".html": "text/html", | |
| ".js": "text/javascript", | |
| ".css": "text/css" | |
| }; | |
| // Load default_file | |
| if (filePath == './') { | |
| filePath = './'+default_file; | |
| } | |
| // Set content type | |
| contentType = cTypes[path.extname(filePath)] || 'text/plain'; | |
| function logOutput(response,file){ | |
| String.prototype.rpad = function(padString, length) { | |
| var str = this; | |
| while (str.length < length) | |
| str = str + padString; | |
| return str; | |
| }; | |
| var cur_time, | |
| d = new Date(), | |
| ampm = 'am', | |
| hour = d.getHours(), | |
| min = d.getMinutes(), | |
| sec = d.getSeconds(), | |
| month = d.getMonth() + 1, | |
| day = d.getDate(), | |
| year = d.getFullYear(), | |
| warn; | |
| (min<=9) ? min = '0'+min : min=min; | |
| (sec<=9) ? sec = '0'+sec : sec=sec; | |
| cur_time = hour + ':' + min + ':' + sec; | |
| (response!==200) ? warn = '!#> ' : warn = ' '; | |
| console.log(warn+ ' Response '+response+': '+file.rpad(' ',50)+request.connection.remoteAddress.rpad(' ',25)+month+'/'+day+'/'+year+' at '+cur_time); | |
| } | |
| // Start checks | |
| path.exists(filePath, function(exists) { | |
| if (exists) { | |
| fs.readFile(filePath, function(error, content) { | |
| if (error) { | |
| response.writeHead(500); | |
| response.end(); | |
| logOutput(500,filePath); | |
| } | |
| else { | |
| response.writeHead(200, { 'Content-Type': contentType }); | |
| response.end(content, 'utf-8'); | |
| logOutput(200,filePath); | |
| } | |
| }); | |
| } | |
| else { | |
| response.writeHead(404); | |
| response.end(); | |
| logOutput(404,filePath); | |
| } | |
| }); | |
| }).listen(port); | |
| console.log("Server Started on "+port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment