[英]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.