I'm having trouble modifying a global variable in a callback.
I need to reload the data from a file every hour. It works fine if I use readFileSync
but not if I use the normal readFile
:
var MY_GLOBAL = {};
fs.readFile("some_path", function (err, data) {
if (err) throw err;
MY_GLOBAL.some_name = data;
});
setInterval(function() {
fs.readFile("some_path", function (err, data) {
if (err) throw err;
MY_GLOBAL.some_name = data;
}
}, 60 * 60 * 60 * 1000);
I have another module named router.js
which contains all the routing for my application.
I call it using: router(app, MY_GLOBAL)
.
My issue is that although MY_GLOBAL
gets set in the readFile
callback, it doesn't update in the router. I need to access the updated data every hour.
I can suggest several things to check.
First, I would double check that the callback function is executing for certain using console.log
or alert
.
I would also like to point out that objects are passed by reference in Javascript, which means that the object passed in to router
is a reference to MY_GLOBAL
, not a copy of MY_GLOBAL
. Where this can go wrong is if somewhere you reassigned MY_GLOBAL. I would make sure that you did not reassign MY_GLOBAL anywhere.
Also, if data
is an object (as opposed to a string, number, or boolean), you need to check that it doesn't get reassigned, either. For example, if you read the value of MY_GLOBAL.some_name inside of router
, it is possible that you could retain a reference to an old version after data
is assigned to MY_GLOBAL.some_name.
If its a global statement why not try to use the module
keyword such a lot of people does with the window
.
another thing. You want the function code to be executed every hour. you are putting one extra 60 multiplication into the second parameter. try this.
module.MY_GLOBAL = {};
var callbackFunction = function(){
fs.readFile("some_path", function (err, data) {
if (err) throw err;
module.MY_GLOBAL.some_name = data;
}
};
callbackFunction();
setInterval(callbackFunction , 60 * 60 * 1000); // 360000 == 1 hour
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.