Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created September 21, 2010 22:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/590688 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/590688 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);
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";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment