简体   繁体   中英

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

So I have 2 files a mapgen.js and a main.js. In mapgen.js there is a function that generates a giant 2d array. 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. 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:

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

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. I would write it to a file but is that not much slower to read and edit than keeping it in the ram? Previously I had gotten past this by keeping everything in 1 file but now I need to clean it all up.

I'm not an expert but if you put one condition in mapgen.js that don't work ?

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?

Requiring the module won't automatically invoke the function. You can do that in the main.js file.

mapgen.js

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

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.

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