[英]Redefining nested function's variable from each call to parent in JavaScript?
[英]NodeJS - Get variable from another file without redefining it each call?
所以我有2个文件mapgen.js和main.js。 在mapgen.js中,有一个函数可以生成巨大的2d数组。 我想在main.js中使用此aray,但不希望生成映射的函数在main.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
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.
我知道我必须在某个地方进行module.exports,但是我认为那仍不能解决我的问题。 我会将其写入文件,但是读取和编辑它并没有比将其保留在ram中慢多少? 以前我通过将所有内容保存在1个文件中来解决了这个问题,但是现在我需要清理所有内容。
我不是专家,但是如果您在mapgen.js中输入一个条件不起作用?
var map;
function mapGen(){
if(!map){
//your code here
map = map contents!
}
}
将其与全局变量和/或module.exports 结合使用请参阅如何在node.js中使用全局变量?
要求模块不会自动调用该函数。 您可以在main.js文件中执行此操作。
module.exports = function mapGen() {
return [/* hundreds of items here. */];
};
// 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.