简体   繁体   English

Node.js 导出变量

[英]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.我正在编写一个 Node.js 模块,我需要将变量数据从主文件传递给函数。 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 ".但是从apiwrapper.js文件中,这两个变量的值总是“ undefined ”。

How can I fix this?我怎样才能解决这个问题?

The value that is imported to the other module is module.exports .导入到另一个模块的值是module.exports So, what you assign to module.exports is exported.因此,您分配给module.exports已导出。 Whatever was assigned earlier to it is lost.之前分配给它的任何东西都丢失了。

The relation between module.exports and exports is that they refer to the same object initially: module.exportsexports之间的关系是它们最初指的是同一个对象:

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.但是,您正在为module.exports分配一个新对象,因此现在它们都引用了不同的对象。

A simple solution is to assign the new object to exports as well and then assign the other properties:一个简单的解决方案是将新对象也分配给exports ,然后分配其他属性:

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.在您的情况下,“module.exports”正在覆盖之前导出的变量。 Which is the reason you are getting undefined for those.这就是您对这些未定义的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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