public
Last active

  • Download Gist
rx_server.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
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);
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 Rx.Observable.If(function() { details.exists; },
fs.stat(details.localpath).Select(function(stat) {
details.exists = !stat.isDirectory();
return details;
}),
Rx.Observable.Return(details));
});
});
 
var found = existent.Where(function(details) { return details.exists });
var fnf = existent.Where(function(details) { return !details.exists });
 
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.statusCode = 200;
details.data = data;
return details;
})
.Catch(Rx.Observable.CreateWithDisposable(function(observer) {
details.statusCode = 500;
details.data = "Cannot read file";
return Disposable.Empty;
}));
});
 
withData.Subscribe(function(details) {
if(details.statusCode == 200) {
details.response.writeHead(details.statusCode, { 'Content-Type': GetContentTypeForExtension(details.extension) });
details.response.write(details.data);
}
else {
details.response.writeHead(details.statusCode, { 'Content-Type': 'text/plain' });
details.response.write(details.data);
}
details.response.end();
});
 
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";
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.