Reputation: 945
I am writing a Node.js module and I need to pass variable data from the main file to the functions. I am doing this:
var region;
var api_key;
exports.region = region;
exports.api_key = api_key;
module.exports = {
getSummonerId: function(sum, callback) {
var summoners = {};
var summoner = sum.replace(/\s+/g, '');
request("https://na.api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + summoner + "?api_key=" + api_key, function(error, response, body) {
summoners[summoner] = JSON.parse(body);
callback(summoners[summoner][summoner].id);
});
}
}
And in the main file:
var lol = require('./apiwrapper.js');
lol.api_key = "example";
lol.region = "las";
lol.getChampions(function(data) {
console.log(data);
})
But from apiwrapper.js file, those two variables' value are always "undefined".
How can I fix this?
Upvotes: 6
Views: 25791
Reputation: 6154
Use:
module.exports = {
region: my_region,
api_key: my_api_key,
getSummonerId: function(sum, callback) {
var summoners = {};
var summoner = sum.replace(/\s+/g, '');
request("https://na.api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + summoner + "?api_key=" + api_key, function(error, response, body) {
summoners[summoner] = JSON.parse(body);
callback(summoners[summoner][summoner].id);
});
}
}
In your case, "module.exports" is overwriting the previously exported variables. Which is the reason you are getting undefined for those.
Upvotes: 1
Reputation: 816262
The value that is imported to the other module is module.exports
. So, what you assign to module.exports
is exported. Whatever was assigned earlier to it is lost.
The relation between module.exports
and exports
is that they refer to the same object initially:
var exports = module.exports = {};
So, assigning a property to either of them mutates the same object. However, you are assigning a new object to module.exports
, so now both of them reference different objects.
A simple solution is to assign the new object to exports
as well and then assign the other properties:
exports = module.exports = {...};
exports.region = region;
If you want to keep the order of the statements, then you have to extend the default exports object, instead of creating a new one:
Object.assign(exports, { ... });
Upvotes: 13