Read the statement by Michael Teeuw here.
Module development node_helper.js config loading
-
Hi folks,
I’m writing a module at the moment and have most of it covered, except loading in my config, some functions seem able to access this.config and others don’t
So first, I’m loading in config like this in node_helper.js:socketNotificationReceived: function(notification, payload) { switch(notification) { case "INIT": this.initConfigs(payload); break initConfigs: function(config) { this.config = config; this.sendSocketNotification('INIT-DONE'); this.init = true; },
And I send that from the main.js by doing:
this.sendSocketNotification("INIT", this.config);
Which works, so in most functions I can then call
this.config.MyVariable and output it.
However in some functions if I try and call the same variable, I get an exception error:[11:17:32.435] [ERROR] TypeError: Cannot read property 'verbose' of undefined
So it seems inconsistent.
How would I define this.config in node_helper.js to be a global variable, should I change reference, move it to a var at the top of node_helpher.js and set it there rather than using the internal this. functions for variable definitions?
Thanks in advance. -
@andyb2000 the problem is that some functions are in callbacks from library services, and ‘this’ at the time is relative to the LIBRARY…
if you do var self=this at the beginning of the surrounding function, and use self. instead, javascript will figure it out…
or, use the newer callback definition (arrow functions) ()=>{}
which maintain the outer context , where function(){} does not
the arrow function operator requires a newer level of javascript then when MM was originally written, but has been available since node 6 I think…(we are using node 10) -
Aha, thank you that’s set me on the right path!
It was indeed when calling it from another service, in this case a setInterval event was calling it which got it confused. Thanks for the suggestion on the newer callback, I solved it in the slightly older low-tech way:
this.timer_socketforever = setInterval(()=>{ this.my_control(this.config) }, 30000);
So that the config info was passed as a parameter.
Problem solved, thank you! -
@andyb2000 you did perfect!!
glad u got it working
u didn’t NEED to pass it, as this.my_control() worked, the ‘this’ pointer is correct inside the function…