node.js - Express: passing options to an included server -
i develop express website can run either stand-alone or part of larger server while allowing degree of configuration.
for example, have large main server in server.js
, write server app.js
defines route /*
provide small service. want able either:
- run
app.js
standalone, provide routes throughlocalhost:port/
- define route within
server.js
maps server, example/app/*
allowapp.js
handle requests.
reading through smashing node, see if define express server , routes in app.js
, can use: server.use('/app', require('app.js')
gain use of routes. problem approach not see how pass configuration options app.js
.
you write app.js module callable function:
var express = require("express"); var app; // <-- note global var initialize = function(conf) { if (app) { return app; } conf = conf || {}; app = express(); // here goes configutation code, example: if (conf.static) { app.use(express.static(conf.static)); } return app; }; if (require.main === module) { // if standalone, fire initialize({ static: __dirname + "/public" }); } // , export module.exports = exports = initialize;
and in other file:
var app = require("app.js")({ static: __dirname + "/public" });
note singleton, further calls module function return same server:
app == require("app.js")();
i'm sure can tweak needs.
Comments
Post a Comment