Layers – Layered Architecture for node.js made easy
June 28, 2011 – 6:37 pmIn my previous post A Layered Node.js Architecture using Express I wrote on the benefits of using a layered architecture and how to implement one in a node.js web app. This post goes one step further by introducing Layers, a module which will help automatically load and neatly setup the layers (and routes) of your web app.
Layers currently only supports Express, but adding support for other frameworks is simple. Feel free to submit a pull request!
The following is a description of how Layers works. For the impatient or code-hungry there is the working Layered Express example from which the following snippets are taken.
Layers performs two basic operations:
- Loads all layer javascript files.
- Loosely couples the layers and adds routes.
Installing
$ npm install layers
Example app
Simply require it and instantiate with your app, the path to your layers, a function which returns your wiring (more on this in the next section) and, optionally, an options object. i.e.
var Layers = require('layers').Express, wiring = require('./layers/wiring'); new Layers(app, __dirname + '/layers', wiring);
File Layout
In this example the layout of the directories is:
__dirname
- layers
- controllers
- services
- viewsLoading Layers
Each directory nested immediately within the layers directory defines a layer.
Each of these layer directories are recursively scanned for javascript files which are imported using require. The result of the require is inspected for two possibilities:
- An object
- A function


