Mikael's blog

A developers sixth time trying to maintain a blog

Source Code - Root / controllers / staticFileController.js
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
/*****************************************
 *   Static File Controller
 *****************************************
 *   Author:  mikael.lofjard@gmail.com
 *   Website: http://lofjard.se
 *   License: MIT License
 ****************************************/
  
var StaticFileController = (function() {
  
    var url = require('url');
    var nodestatic = require('node-static');
      
    var dm = require('../domainManager').DomainManager;
      
    var fileServers = {};
    var fallbackFileServer = new nodestatic.Server();
      
    return {
          
        init: function() {
            var lastwwwroot = '';
              
            var allRoots = dm.getAllWwwRoots();
            for(var i in allRoots) {
                var wwwroot = allRoots[i];
                console.log('Static File Controller: Creating node-static server for ' + wwwroot);
                fileServers[wwwroot] = new nodestatic.Server(wwwroot);
            }
        },
          
        file: function(request, response) {
            if (!dm.isConfiguredDomain(request)) {
                StaticFileController.error(request, response, 404);
                return;
            }
              
            fileServers[dm.getCurrentWwwRoot(request)].serve(request, response, function (err, result) {
                if(err) {
                    StaticFileController.error(request, response, 404);
                    return;
                }
            });
  
            return;
        },
  
        error: function(req, res, status) {
            fallbackFileServer.serveFile('./content/404.html', status, {}, req, res);
        }
  
    };
  
}());
  
typeof(exports) != 'undefined' ? exports.StaticFileController = StaticFileController : null;