Ok, I still have not fully understand the best way to require modules in Node that will be shared among several js files. For example: If I have a main app.js and two other files: routes1.js and routes2.js containing (mostly) exported routes that are required in app.js.
I think we all agree about that if I need – for example – UnderscoreJs. I just repeat this line of code in every file that needs it.
var _ = require('underscore');
But how about modules that expose a function/constructor, like this:
var email = require('powerdrill')('YOURAPIKEY');
If i repeat this code in every file, I end up with three instances of the powerdrill object, right? Even though this works just fine I cant help feeling this ain't right.
Or maybe its totaly viable and fine if I just want to require it in a small number of files?
Question: For all of you who have been working with Node for a while now, and feel comfortable with the way you require things. How do you "solve" case 2 above? Maybe there is no right way, but a little guidance would be appreciated.
You could write your own common module and include that instead. Though, I'd prefer what you're doing already but I guess it's a matter of taste.
This is written without testing it, so it probably is not the right way to do it. Maybe you'll get some ideas:
// utils.js
// ======== define the module
var myEmail = require('powerdrill')('YOURAPIKEY');
module.exports = {
email: myEmail
};
// app.js
var utils = require('./utils');
utils.mail.useIt();
This way, I think everyone that requires utils.js will use the same myEmail instance.