Reputation: 15
I'm trying to implement a variable system for my html web pages. That's why I wrote a function that will take some string, search it for variables, replace them with their corresponding value and the give the new string back:
//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);
};
This part works without issues. Its also able to replace multiple instances of the same variable. The problem is now the external variables.js file. I made an external file for these as I will probably a few dozens of these in the future. This is the variable.js file:
//Container with all variables
let variables = {
'landing_videoID': global.newestVideo.id,
'landing_time': new Date(Date.now()).toUTCString()
};
//Export the variables
module.exports = variables;
When the handlers.insertVariables function gets called for the first time, it will receive the up-to-date values. But these then are not changing anymore. Is there something that I'm doing wrong, or is my attempt just bs in general? Thanks for your help!
Upvotes: 0
Views: 170
Reputation: 952
Module is cached after first require
. One way to solve this problem is to export as function and call it every time as follows:
So, refactor variable.js
as follows:
//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;
Then, require
variable.js
like this:
//Load variables
let variables = require('./variables.js')();
Upvotes: 1