Reputation: 197
I'm puzzled. I expect that when I load a node module, the local variables will persist within the module but that doesn't seem to be happening.
My node module:
var Mailgun = require("mailgun-js");
var api_key, domain;
exports.config = function(config){
api_key = config.api_key;
domain = config.domain;
console.log(config);
};
exports.mailgun = new Mailgun({apiKey: api_key, domain: domain});
Then I use it like this:
var mailgunMod = require("./config/mailgun");
var config = {
api_key: 'key-xxxxxxxxxxxxxxxxxxxxxxxx',
domain: 'xxxxx.com'
};
mailgunMod.config(config);
var mailgun = mailgunMod.mailgun;
mailgun.messages().send(data, function (err, body) {...};
But the values of api_key and domain both become undefined. Why?
Edit: Tried the factory pattern like so:
exports.getMailgun = function(){
return new Mailgun({apiKey: api_key, domain: domain});
}
Works great. But... before doing that I tried this which doesn't work and I can't see why:
var Mailgun = require("mailgun-js");
var api_key, domain;
var mailgun;
exports.config = function(config){
api_key = config.api_key;
domain = config.domain;
mailgun = new Mailgun({apiKey: api_key, domain: domain});
console.log(config);
};
exports.mailgun = mailgun;
It doesn't 'New' in the exports now but still doesn't work (comes back .mailgun undefined). Why?
Upvotes: 3
Views: 966
Reputation: 4265
They don't "become" undefined, they start undefined.
When your first module is executed (during the require() call in the second), the values passed to the mailgun constructor are in fact undefined. You create a new Mailgun instance, with this undefined value, and export it.
The fact that the value passed to that constructor is passed from a variable that later gets assigned to (when you call config()) does not change the fact that you created a Mailgun with some undef arguments... it never gets re-created, and its init values will not change unless you explicitly change them.
You're not passing a reference (to the variable, for example) into that constructor, you're passing the value.
Maybe try a factory pattern, something like
getMailgun(config) { return new Mailgun(config); }
That's cleaner, as it does not rely on "module" scoped variables (really, modules are not scopes, but execute in closures that hold the locals)
Upvotes: 4