Reputation: 2574
I am working on an expressjs application that loads configuration data from a remote data store. I have all the configuration code in a module.
Modules that I require after I require the configuration module in the main express application also depend on the configuration request being completed.
Is there a way to pause the start-up of the express application until the configuration module is completed? Or a way to guarantee that config has been loaded before the rest of the application continues. I'd prefer to not have to put logic in each module to check that config has been loaded.
// config.js
var zmq = require('zmq');
var sock = zmq.socket('req');
sock.connect(endpoint);
sock.send('config');
sock.on('message', function(data) {
module.exports = JSON.parse(data.toString());
});
// server.js Main application
....
var config = require('./config'); // contains connection information for DB, 3rd party apps, etc...
var db = require('./db'); // Uses the config to know where to connect
var logger = require('./logger');
....
var debug = config.isDebug;
...
// db.js module
var config = require('./config');
var host = config.host
var port = config.port
....
// logger.js module
var config = require('./config');
var logLevel = config.logLevel;
....
Upvotes: 1
Views: 997
Reputation: 276436
The easiest way is that config would let other modules know when it is done.
Instead of returning nothing, the exports of the config module should be a function that accepts a callback. When the module is done loading (or if it is already loaded) the callback executes. That code would be something like:
// db.js module
var config = require('./config');
config(function(err, config) {
if(err) throw err; // could not load configuration
var host = config.host
var port = config.port
})
Upvotes: 1