Created
January 14, 2012 01:47
-
-
Save ww24/1609822 to your computer and use it in GitHub Desktop.
js2coffee http.js > http.coffee
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
http = require("http") | |
path = require("path") | |
url = require("url") | |
fs = require("fs") | |
configure = (settingsFile) -> | |
settings = JSON.parse(fs.readFileSync(settingsFile, "utf8")) | |
items = [ settings.host, settings.port ] | |
item = "" | |
points = [] | |
point = "" | |
pointer = 0 | |
i = undefined | |
j = undefined | |
i = 0 | |
while items.length > i | |
item = items[i] | |
if typeof (item) is "string" and item.indexOf("process.env.") isnt -1 | |
points = item.split("||") | |
j = 0 | |
while points.length > j | |
point = points[j].replace(/^\s+|\s+|'+|"+$/g, "") | |
pointer = point.indexOf("process.env.") | |
point = process.env[point.slice(pointer + 12)] if pointer isnt -1 | |
break if typeof (point) isnt "undefined" | |
j++ | |
items[i] = point | |
i++ | |
settings.host = items[0] | |
settings.port = items[1] | |
settings.docRoot = path.join(__dirname, settings.docRoot) | |
logFile = settings.accessLog | |
if logFile isnt false | |
logFile = path.join(__dirname, settings.accessLog) | |
settings.accessLog = true | |
settings | |
settings = configure(path.join(__dirname, "http.conf")) | |
getDateFormat = (set) -> | |
date = (if (typeof (set) is "undefined") then new Date() else new Date(set)) | |
tt = (t) -> | |
abs = Math.abs(t) | |
String (if (abs < 10) then (if (t < 0) then "-0" + abs else "0" + t) else t) | |
timezoneOffset = -date.getTimezoneOffset() | |
timezoneOffsetH = tt(parseInt(timezoneOffset / 60, 10)) | |
timezoneOffsetM = tt(timezoneOffset % 60) | |
format = [ [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ][date.getDay()] + ",", [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ][date.getMonth()], tt(date.getDate()), date.getFullYear(), tt(date.getHours()) + ":" + tt(date.getMinutes()) + ":" + tt(date.getSeconds()), (if (timezoneOffsetH < 0) then "" else "+") + timezoneOffsetH + timezoneOffsetM ] | |
format.join " " | |
logging = (file, log) -> | |
str = JSON.stringify(log) | |
fd = fs.openSync(file, "a") | |
position = fs.statSync(file).size | |
str = "\n," + str if position isnt 0 | |
fs.writeSync fd, str, position, "utf8" | |
fs.closeSync fd | |
if settings.errorLog isnt false | |
process.on "uncaughtException", (err) -> | |
logging path.join(__dirname, settings.errorLog), | |
date: getDateFormat() | |
error: err | |
getRequestFilePath = (filePath) -> | |
fullPath = false | |
if filePath.slice(-1) is "/" | |
i = 0 | |
l = settings.defFile.length | |
while i < l | |
fullPath = path.join(settings.docRoot, filePath, settings.defFile[i]) | |
break if path.existsSync(fullPath) | |
i++ | |
(if fullPath then fullPath else path.join(settings.docRoot, filePath)) | |
http.createServer((req, res) -> | |
date = getDateFormat() | |
filePath = url.parse(req.url).pathname | |
fullPath = getRequestFilePath(filePath) | |
ext = path.extname(fullPath) | |
path.exists fullPath, (exists) -> | |
statusCode = 200 | |
contentType = "text/plain" | |
body = "" | |
if ext of settings.MIME | |
if exists | |
contentType = settings.MIME[ext] | |
body = fs.readFileSync(fullPath) | |
else | |
statusCode = 404 | |
body = "Not Found\n" + filePath | |
else | |
statusCode = 403 | |
body = "Forbidden\n" + filePath | |
res.setHeader "Date", date | |
headers = settings.httpHeaders | |
for key of headers | |
res.setHeader key, headers[key] if headers.hasOwnProperty(key) | |
method = req.method | |
if method is "GET" or method is "POST" | |
res.writeHead statusCode, | |
"Content-Type": contentType | |
"Content-Length": body.length | |
res.write body | |
else | |
res.writeHead statusCode | |
res.end() | |
if settings.accessLog | |
logging logFile, | |
date: date | |
method: method | |
url: req.url | |
statusCode: statusCode | |
).listen settings.port, settings.host | |
console.log "Server running at http://" + settings.host + ":" + settings.port + "/" |
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
/** | |
* node-web-server | |
* @source https://github.com/ww24/node-web-server | |
* @license MIT License | |
* @version 1.0.6 | |
*/ | |
var http = require('http'), | |
path = require('path'), | |
url = require('url'), | |
fs = require('fs'); | |
// Configure | |
var configure = function (settingsFile) { | |
// Load Settings File | |
var settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8')); | |
// host, port Settings | |
var items = [settings.host, settings.port], | |
item = '', | |
points = [], | |
point = '', | |
pointer = 0, | |
i, j; | |
for (i = 0; items.length > i; i++) { | |
item = items[i]; | |
if (typeof(item) === 'string' && item.indexOf('process.env.') !== -1) { | |
points = item.split('||'); | |
for (j = 0; points.length > j; j++) { | |
point = points[j].replace(/^\s+|\s+|'+|"+$/g, ''); | |
pointer = point.indexOf('process.env.'); | |
if (pointer !== -1) { | |
point = process.env[point.slice(pointer + 12)]; | |
} | |
if (typeof(point) !== "undefined") break; | |
} | |
items[i] = point; | |
} | |
} | |
settings.host = items[0]; | |
settings.port = items[1]; | |
// DocRoot Setting | |
settings.docRoot = path.join(__dirname, settings.docRoot); | |
// AccessLog Setting | |
var logFile = settings.accessLog; | |
if (logFile !== false) { | |
logFile = path.join(__dirname, settings.accessLog); | |
settings.accessLog = true; | |
} | |
return settings; | |
}; | |
var settings = configure(path.join(__dirname, 'http.conf')); | |
// Get Date (Sun, Aug 07 2011 00:00:00 +0000)RFC1123 | |
var getDateFormat = function(set) { | |
var date = (typeof(set) == 'undefined')? new Date() : new Date(set), | |
// Convert to Double-digit (-7 → 07) toString | |
tt = function(t) { | |
var abs = Math.abs(t); | |
return String((abs < 10)? (t < 0)? '-0'+abs : '0'+t : t); | |
}, | |
timezoneOffset = -date.getTimezoneOffset(), | |
timezoneOffsetH = tt(parseInt(timezoneOffset/60, 10)), | |
timezoneOffsetM = tt(timezoneOffset%60), | |
format = [ | |
["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][date.getDay()]+",", | |
["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][date.getMonth()], | |
tt(date.getDate()), | |
date.getFullYear(), | |
tt(date.getHours())+':'+tt(date.getMinutes())+':'+tt(date.getSeconds()), | |
((timezoneOffsetH < 0)?'':'+')+timezoneOffsetH+timezoneOffsetM | |
]; | |
return format.join(" "); | |
}; | |
// Logging (JSON) | |
var logging = function(file, log) { | |
var str = JSON.stringify(log), | |
fd = fs.openSync(file, 'a'), | |
position = fs.statSync(file).size; | |
if (position !== 0) { | |
str = '\n,' + str; | |
} | |
fs.writeSync(fd, str, position, 'utf8'); | |
fs.closeSync(fd); | |
}; | |
// Error logging | |
if (settings.errorLog !== false) { | |
process.on('uncaughtException', function(err) { | |
logging(path.join(__dirname, settings.errorLog), { | |
date : getDateFormat(), | |
error : err | |
}); | |
}); | |
} | |
// Get Request File Path | |
var getRequestFilePath = function (filePath) { | |
var fullPath = false; | |
if (filePath.slice(-1) === '/') { | |
for (var i = 0, l = settings.defFile.length; i < l; i++) { | |
fullPath = path.join(settings.docRoot, filePath, settings.defFile[i]); | |
if (path.existsSync(fullPath)) { | |
break; | |
} | |
} | |
} | |
return fullPath ? fullPath : path.join(settings.docRoot, filePath); | |
}; | |
// Create HTTP Server | |
http.createServer(function (req, res) { | |
var date = getDateFormat(), | |
filePath = url.parse(req.url).pathname, | |
fullPath = getRequestFilePath(filePath), | |
ext = path.extname(fullPath); | |
// Check Request File Exists | |
path.exists(fullPath, function(exists) { | |
var statusCode = 200, | |
contentType = 'text/plain', | |
body = ''; | |
// Check MIME Type | |
if (ext in settings.MIME) { | |
if (exists) { | |
contentType = settings.MIME[ext]; | |
body = fs.readFileSync(fullPath); | |
} else { | |
statusCode = 404; | |
body = 'Not Found\n' + filePath; | |
} | |
} else { | |
statusCode = 403; | |
body = 'Forbidden\n' + filePath; | |
} | |
// HTTP Header | |
res.setHeader("Date", date); | |
var headers = settings.httpHeaders; | |
for (var key in headers) { | |
if (headers.hasOwnProperty(key)) { | |
res.setHeader(key, headers[key]); | |
} | |
} | |
// Check HTTP Method | |
var method = req.method; | |
if (method == "GET" || method == "POST") { | |
res.writeHead(statusCode, { | |
'Content-Type': contentType, | |
'Content-Length': body.length | |
}); | |
res.write(body); | |
} else { | |
res.writeHead(statusCode); | |
} | |
res.end(); | |
// Logging | |
if (settings.accessLog) { | |
logging(logFile, { | |
date : date, | |
method : method, | |
url : req.url, | |
statusCode : statusCode | |
}); | |
} | |
}); | |
}).listen(settings.port, settings.host); | |
console.log('Server running at http://'+settings.host+':'+settings.port+'/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment