Javascript 使用对象作为查找表:值在第一次调用后不会更新
我正在尝试为我的html网页实现一个可变系统。这就是为什么我写了一个函数,它将获取一些字符串,搜索变量,用相应的值替换它们,然后返回新字符串:Javascript 使用对象作为查找表:值在第一次调用后不会更新,javascript,node.js,object,Javascript,Node.js,Object,我正在尝试为我的html网页实现一个可变系统。这就是为什么我写了一个函数,它将获取一些字符串,搜索变量,用相应的值替换它们,然后返回新字符串: //Finish HTML files by replacing variables handlers.insertVariables = function(file, callback){ //Load variables let variables = require('./variables.js'); console.log(vari
//Finish HTML files by replacing variables
handlers.insertVariables = function(file, callback){
//Load variables
let variables = require('./variables.js');
console.log(variables) //For debugging only
//Loop through all possible variables and replace
for(let key in variables){
if(variables.hasOwnProperty(key)){
let find = '{' + key + '}';
let replace = variables[key];
file = file.split(find).join(replace)
//file = file.replace('{' + key + '}', variables[key])
}
}
//Callback the new file
callback(false, file);
};
这部分工作没有问题。它还可以替换同一变量的多个实例。现在的问题是externalvariables.js文件。我为这些做了一个外部文件,因为我将来可能会有几十个这样的文件。这是variable.js文件:
//Container with all variables
let variables = {
'landing_videoID': global.newestVideo.id,
'landing_time': new Date(Date.now()).toUTCString()
};
//Export the variables
module.exports = variables;
当handlers.insertVariables函数第一次被调用时,它将接收最新的值。但这些都不再改变了。是我做错了什么,还是我的尝试只是一般的废话?
谢谢你的帮助 模块在第一次请求后被缓存。解决此问题的一种方法是导出为函数,并按如下方式每次调用它:
//Container with all variables
function getValues()
return {
'landing_videoID': global.newestVideo.id,
'landing_time': new Date(Date.now()).toUTCString()
};
}
//Export the variables
module.exports = getValues;
因此,重构variable.js如下:
//Container with all variables
function getValues()
return {
'landing_videoID': global.newestVideo.id,
'landing_time': new Date(Date.now()).toUTCString()
};
}
//Export the variables
module.exports = getValues;
然后,要求variable.js如下:
//Load variables
let variables = require('./variables.js')();