Search code examples
node.jsflatiron.js

Flatiron js - director - how to do async routing from a table?


I'm starting to get things set up using flatiron as the toolset for a web app.

I'm using director with app.plugins.http, and can't seem to figure out how to create a "catchall" route for static files & 404s - It appears that .get("<RegEx>") only matches the first folder position, so if <RegEx> is /.*, it'll match /foo, but not /foo/bar.

Here's my code, as a better example:

in routes.js:

var routes = {
  /* home
  * This is the main route, hit by queries to "/"
  */
  "/" : {
    get: function(){
      getStatic("html/index.html",_.bind(function(err,content){
        if(err) throw err;
        renderContent(this,content);
      },this));
    }
  },
  /* static files
  * Last rule, if no other routes are hit, it's either a static resource
  * or a 404. Check for the file then return 404 if it doesn't exist.
  */
  '/(.*)' : {
    get : function(){
      getStatic(this.req.url,_.bind(function(err,content){
        if(!err){
          renderContent(this,content);
        } else {
          this.res.writeHead(404);
          // TODO: fancier 404 page (blank currently)
          this.res.end();
        }
      },this))
    }
  }
}

and in my main app file:

/* Define the routes this app will respond to. */
var routes = require('./lib/routes');
/* set up app to use the flatiron http plugin */
app.use(flatiron.plugins.http);
/* loop through routes and add ad-hoc routes for each one */
for(var r in routes){
    var route = routes[r];
    if(!routes.hasOwnProperty(r)) continue;
    for(var method in route){
        if(!route.hasOwnProperty(method)) continue;
        app.router[method](r,route[method]);
    }
}
/* Start the server */
app.listen(8080);

I'd like to be able to keep my routes in a separate module and import them - I'm pretty unclear on if this method or using director and a vanilla http server would be better, but I've tried both ways without any luck.

Here's what I get:

localhost:8080/
>> (content of index file - this works)
localhost:8080/foo
>> (blank page, 404 header)
localhost:8080/foo/bar
>> (no static file for this - I get a 404 header, but the body is now "undefined" - where is this coming from??)
localhost:8080/css/min.css
>> (this file should exist, but the route is never called. I do however still get a 404 header, and get the "undefined" body)

so, I'm assuming the "undefined" body is default behavior for undefined routes.

Is there a way to create a catchall route without adding rules for each depth?


Solution

  • You could try using node-ecstatic which is a static file serving add-on for flatiron. It works well for me and you can find it at:

    https://github.com/colinf/node-ecstatic