After Express App is initialized, I can't add objects to module.exports

131 views Asked by At

server.js

module.exports.a = 'abc';
var app = expressAppConstructor(db);
module.exports.b = 'xyz';
console.log(JSON.stringify(module.exports)); // --> {"a":"abc","b":"xyz"}

exportsLog.js

var io = require('./server');
console.log(JSON.stringify(io)); // --> {"a":"abc"} Note b: xyz is missing

How can I add b to module.exports after the Express App is initialized?

I'm on the mean.js Stack and the mentioned files above are server.js, expressConstructorFunction is require(./config/express.js)

See original contents of server.js, config/express.js

1

There are 1 answers

0
CatDadCode On BEST ANSWER

After debugging with your actual app I've discovered the reason the second setting doesn't work. It does work, but when you initialize your express app you are requiring the server file in one of your routes.

node server.js -> exports.a = 'abc'; -> expressAppConstructor ->

config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
  require(path.resolve(routePath))(app);
});

-> in one route file loaded via the above, this runs: require('server.js'); -> now finally the stack returns to the server file and does: exports.b='xyz';, but the module has already been required and cached by your route file.

I would actually be worried that you're starting the server over and over each time you require the file. Though I think it's not breaking because node caches modules that have been required so the logic isn't running, but the exports on the cached server module only has the first assignment since it was required by your route file before the second assignment to exports even occurs. By the time your route file tries to load the server file, it has only run up to the app initialization line. Anything added to exports after you've required it in your route file obviously isn't going to make it onto the exported data.