简体   繁体   English

NodeJS-从另一个文件获取变量,而无需在每次调用时重新定义它?

[英]NodeJS - Get variable from another file without redefining it each call?

So I have 2 files a mapgen.js and a main.js. 所以我有2个文件mapgen.js和main.js。 In mapgen.js there is a function that generates a giant 2d array. 在mapgen.js中,有一个函数可以生成巨大的2d数组。 I want to use this aray in main.js but don't want the function that generates the map to run everytime its 'required' in main.js. 我想在main.js中使用此aray,但不希望生成映射的函数在main.js中每次“必需”运行时都运行。 I also want to be able to edit the map array eventually. 我还希望最终能够编辑地图数组。

Example: (not real code just wrote some crap to show what the issue is) 示例:(不是真正的代码,只是写了一些废话来说明问题所在)

mapgen.js: mapgen.js:

var map;
function mapGen(){
    //make the map here
      this function takes like 2 seconds and some decent CPU power, so 
      don't want it to ever run more than once per server launch
    map = map contents!
}

main.js main.js

var map = require mapgen.js;
console.log(map.map);
//start using map variable defined earlier, but want to use it without
  having to the run the big funciton again, since it's already defined.

I know i have to module.exports somewhere but I dont think that will solve my problem still. 我知道我必须在某个地方进行module.exports,但是我认为那仍不能解决我的问题。 I would write it to a file but is that not much slower to read and edit than keeping it in the ram? 我会将其写入文件,但是读取和编辑它并没有比将其保留在ram中慢多少? Previously I had gotten past this by keeping everything in 1 file but now I need to clean it all up. 以前我通过将所有内容保存在1个文件中来解决了这个问题,但是现在我需要清理所有内容。

I'm not an expert but if you put one condition in mapgen.js that don't work ? 我不是专家,但是如果您在mapgen.js中输入一个条件不起作用?

var map;
function mapGen(){
    if(!map){
       //your code here
       map = map contents!
    }
}

Combine that with global variable and/or module.exports See How to use global variable in node.js? 将其与全局变量和/或module.exports 结合使用请参阅如何在node.js中使用全局变量?

Requiring the module won't automatically invoke the function. 要求模块不会自动调用该函数。 You can do that in the main.js file. 您可以在main.js文件中执行此操作。

mapgen.js mapgen.js

module.exports = function mapGen() {
  return [/* hundreds of items here. */];
};

main.js main.js

// Require the module that constructs the array.
const mapGen = require('./mapgen');

// Construct the array by invoking the mapGen function and 
// store a reference to it in 'map'.
const map = mapGen(); // `map` is now a reference to the returned array.
// Do whatever you want with 'map'.
console.log(map[0]); // Logs the first element.

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

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