Created
July 8, 2010 18:59
-
-
Save bga/468437 to your computer and use it in GitHub Desktop.
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
(function() | |
{ | |
var sys = require('sys'), | |
http = require('http'), | |
fs = require('fs'), | |
Script = process.binding('evals').Script; | |
var extToMimeMap = | |
{ | |
'.txt': 'text/plain', | |
'.js': 'text/javascript', | |
'.css': 'text/css', | |
'.html': 'text/html', | |
'.htm': 'text/html' | |
}; | |
var _urlExt = function(url) | |
{ | |
var begin = 0, end = url.length, point, i; | |
if((i = url.lastIndexOf('#', end)) > 0) | |
end = i; | |
if((i = url.lastIndexOf('?', end)) > 0) | |
end = i; | |
if((i = url.lastIndexOf('.', end)) < 0) | |
return null; | |
point = i; | |
if((i = url.lastIndexOf('/', end)) > -1) | |
begin = i; | |
if(begin >= point) | |
return null; | |
return url.substring(point, end); | |
}; | |
var _log = function() | |
{ | |
sys.puts.apply(sys, arguments); | |
}; | |
var _isDynamicUrl = function(url) | |
{ | |
return url.indexOf('.app.js') > -1; | |
}; | |
var _server = function (req, res) | |
{ | |
var url = unescape(req.url); | |
_log(url); | |
url = ('.' + url).replace(/\/(?:\?|#|$)/, '/index.html'); | |
url = url.slice(0, url.lastIndexOf('?') >>> 0); | |
if(_isDynamicUrl(url)) | |
{ | |
fs.readFile( | |
url, | |
function(err, data) | |
{ | |
if(err) | |
{ | |
res.writeHead(404); | |
res.end(); | |
} | |
//_log(data); | |
//Script.runInThisContext('(' + data + ')();', url); | |
Script.runInNewContext('(' + data + ')(req, res);', {req: req, res: res, sys: sys, setTimeout: setTimeout, setInterval: setInterval, require: require}, url); | |
} | |
); | |
} | |
else | |
{ | |
fs.readFile( | |
url, | |
function(err, data) | |
{ | |
if(err) | |
{ | |
res.writeHead(404); | |
res.end(); | |
} | |
res.writeHead(200, {'Content-Type': extToMimeMap[_urlExt(url)] || 'text/plain'}); | |
res.end(data); | |
} | |
); | |
} | |
} | |
http.createServer(_server).listen(80); | |
sys.puts('Server running at http://127.0.0.1:80/'); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment