server.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var http = require('http');
  2. var staticServe = require('node-static');
  3. var fs = require('fs');
  4. function Server(port){
  5. this._html = '<html><body>Nothing has happened yet. But stay tuned!</body></html>';
  6. this._simpleHtml = fs.readFileSync(__dirname+'/resources/simple.html');
  7. this._json = {};
  8. this.port = port;
  9. var staticServer = new staticServe.Server(__dirname+'/resources');
  10. var that = this;
  11. this._httpServer = http.createServer(function (request, response) {
  12. that.processRequest(request.url,request.headers['content-type'],response);
  13. // static file fallback
  14. request.addListener('end', function(){
  15. staticServer.serve(request,response);
  16. });
  17. });
  18. };
  19. Server.prototype.updateJson = function(json){
  20. this._json = json;
  21. }
  22. Server.prototype.updateHtml = function(html){
  23. this._jasmineHtml = html;
  24. }
  25. Server.prototype.processRequest = function(url,mime,response){
  26. switch(url){
  27. case '/':
  28. response.writeHead(200, {'Content-Type': 'text/html'});
  29. response.end(this._simpleHtml);
  30. break;
  31. case '/jasmine':
  32. response.writeHead(200, {'Content-Type': 'text/html'});
  33. response.end(this._jasmineHtml);
  34. break;
  35. case '/json':
  36. response.writeHead(200, {'Content-Type': 'application/json'});
  37. response.end( JSON.stringify(this._json) );
  38. break;
  39. default:
  40. break;
  41. }
  42. };
  43. Server.prototype.start = function(){
  44. this._httpServer.listen(this.port, "127.0.0.1");
  45. console.log("Started http server on port ", this.port);
  46. };
  47. var server;
  48. exports.start = function(port, callback){
  49. server = new Server(port);
  50. server.start(function(){
  51. callback();
  52. });
  53. };
  54. exports.stop = function(callback){
  55. if(server) server.stop();
  56. };
  57. exports.updateJson = function(json){
  58. if(server) server.updateJson(json);
  59. };
  60. exports.updateHtml = function(html){
  61. if(server) server.updateHtml(html);
  62. };