4

In my app.js I set the following setting

app.set('mailTemplatesDir', __dirname + '/mails');

Now I would like to read the value of 'mailTemplatesDir' in one of my controllers, how can I access the setting there? I would prefer not to make app a global variable.

1 Answer 1

4

If you've created your app with the usual call to createServer() then there really is no other way to access option settings without going through the object returned by that function. Express does not cache the server object but simply returns the result of new on the object.

If you've created your application with the standard express boilerplate generated for you, you likely have a line creating app that looks like:

var app = module.exports = express.createServer();

This does not actually create app as a global variable but does make it available as a module export. You can access your mailTemplatesDir option from another module by requiring your app.js module this way:

var templateDir = require('./app').set('mailTemplatesDir');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, tried you idea by implementing the app = module.exports = express.createServer() approach, however, when I require the app in another file I always get an EADDRINUSE error (I guess the server tries to re-listen on the port every time I require the app module). Any idea how to solve that?
Hmm... the example I tried seemed to work. I went ahead and put my example up on github. I can read back the option in a separate module before the listen is called and in a callback function as the result of getting an http request without having the problems you describe. Perhaps you can post your app.js?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.