Express: passing options to an included server

I would like to develop an Express website that can run either stand-alone or as part of a larger server while allowing a degree of configuration.

For example, say I have a large main server in server.js and I write another server app.js that defines a route /* to provide a small service. I want to be able to either:

  • run app.js standalone, which will provide its routes through localhost:port/
  • define a route within server.js that maps to this server, for example so that /app/* will allow app.js to handle requests.

Reading through Smashing Node, I see that if I define an Express server and its routes in app.js, I can use: server.use('/app', require('app.js') to gain use of its routes. The problem with this approach is that I do not see how to pass any configuration options to app.js.

You could write your app.js module as a callable function:

var express = require("express");

var app; // <-- note the global

var initialize = function(conf) {
    if (app) {
        return app;
    }

    conf = conf || {};

    app = express();

    // here goes the configutation code, for example:
    if (conf.static) {
        app.use(express.static(conf.static));
    }
    return app;
};

if (require.main === module) {
    // if standalone, fire it
    initialize({ static: __dirname + "/public" });
}

// and export
module.exports = exports = initialize;

and then in other file:

var app = require("app.js")({ static: __dirname + "/public" });

Note that it is a singleton, so further calls to the module function will return the same server:

app == require("app.js")();

I'm sure you can tweak it to your needs.