Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created September 13, 2010 23:54
Show Gist options
  • Save mattpodwysocki/578274 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/578274 to your computer and use it in GitHub Desktop.
var sys = require('./rx_sys');
var http = require('./rx_http');
var fs = require('./rx_fs');
var url = require('url');
var path = require('./rx_path');
var serverData = http.createServer();
var requests = serverData.Select(function(details) {
details.url = url.parse(details.request.url);
details.localpath = path.join(process.cwd(), details.url.pathname);
details.extension = path.extname(details.url.pathname);
details.isJssp = details.extension == ".jssp";
return details;
});
var existent = requests.SelectMany(function(details) {
return path.exists(details.localpath).Select(function(exists) {
details.exists = exists;
return details;
})
.SelectMany(function(details) {
return fs.stat(details.localpath).Select(function(stat) {
details.isDirectory = stat.isDirectory();
return details;
});
});
});
var found = existent.Where(function(details) { return details.exists && !details.isDirectory; });
var fnf = existent.Where(function(details) { return !details.exists || details.isDirectory; });
fnf.Subscribe(function(details) {
details.response.writeHead(404, {'Content-Type': 'text/plain'});
details.response.write('File Not Found: ' + details.url.href);
details.response.end();
});
var withData = found.SelectMany(function(details) {
return fs.readFile(details.localpath).Select(function(data) {
details.data = data;
return details;
}).Catch();
});
var staticWithData = withData.Where(function(details) { return !details.isJssp; });
staticWithData.Subscribe(function(details) {
details.response.writeHead(200, { 'Content-Type': GetContentTypeForExtension(details.extension) });
details.response.write(details.data);
details.response.end();
});
var jssp = withData.Where(function(details) { return details.isJssp; });
jssp.Subscribe(function(details) {
try {
var implementation = eval(details.data);
implementation(details);
}
catch(e) {
sys.puts('error: ' + e);
details.response.writeHead(501, { 'Content-Type': 'text/plain' });
details.response.write('Internal Server Error');
details.response.close();
}
});
serverData.server.listen(8000);
sys.puts('Server running at http://127.0.0.1:8000/');
function GetContentTypeForExtension(extension) {
switch(extension.toLowerCase()) {
case ".html":
return "text/html";
case ".js":
return "application/javascript";
case ".jpg":
return "image/jpeg";
case ".png":
return "image/png";
default:
return "text/plain";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment