Export Variable NodeJS

I am writing a nodejs module and I need to pass variable data from main file to functions, I do 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 these two variable values ​​are always " undefined ".

Can anyone point me in the right direction?

Thanks in advance.

+3


source to share


2 answers


The value to be imported into another module is module.exports

. So, what you assign module.exports

is exported. Everything that was previously assigned is lost.

The connection between module.exports

and exports

is that they first refer to the same object:

var exports = module.exports = {};

      

So, assigning a property to any of them mutates the same object. However, you are assigning a new object module.exports

, so now they both refer to different objects.



A simple solution is to assign a new object exports

and then assign other properties:

exports = module.exports = {...};
exports.region = region;

      

If you want to preserve the order of the statements, then you need to extend the default export object instead of creating a new one:

Object.assign(exports, { ... });

      

+11


source


Why not 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" overwrites previously exported variables. It is for this reason that you get undefined for them.

+1


source







All Articles