简体   繁体   中英

Node.js export variable

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 :

var lol = require('./apiwrapper.js');

lol.api_key = "example";
lol.region  = "las";


lol.getChampions(function(data) {
  console.log(data);
})

But from file, those two variables' value are always " ".文件中,这两个变量的值总是“ ”。

How can I fix this?

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, { ... });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM