Node namespace confusion on my part (?)


#1

I have a working node (node-red-contrib-mytimeout) and I have a user who has 12 of these nodes in 1 tab. I'm investigating why some nodes, sometimes fails to finish counting down (see below),. I've seen this before occur when the ticks (they are what I count down) is set to -1 before reaching 0. While I don't think that can happen in my current code.

What I'd like to know is if the node's might share namespace if the nodes all had the same node? Or is it something else I might not yet understand.


#2

I didn't go in depth into you code, so this is only a guess:

Try to change all global vars to this e.g.:

var timeout     = parseInt(n.timer||30); 
this.timeout =  parseInt(n.timer||30); 

#3

Huge thanks, I don't quite understand the scope of Javascript (as my code shows). I'll fix that as I think I have a couple of values like that.


#4

@ncherry, as an aside is this really what you want, or do you want
this.timeout = parseInt(n.timer)||30;


#5

I forget why that came about ... but I'll correct it to parseInt(n.timer)||30. When I first created this node it was a bit of cargo cult programming. Since then I've let well enough alone. Now is s good time to finish the rest of the cleanup. There is still a lot of cruft left that needs to be removed or corrected.

Thanks

Update: I recall now, if n wasn't defined it would get an exception. With parseInt(n.timer||30) I'd get 30 instead of the exception. Probably not a good way of dealing with the exception but as I said, cargo cult programming. I understand nodes a bit better now. Though I'm certain I have a lot more to learn


#6

Perfectly reasonable approach on my book. The parseInt must have something valid to work on.


#7

That is fine if you are concerned about n.timer not defined. However, if n.timer was set to "hello" for example then n.timer||30 would be "hello" and parseInt would return NaN. However parseInt("hello")||30 is 30. As I said, it depends what you are trying to protect against. I don't know what the timer is without looking at the code again, but also note that will not be able to set it to 0 with either of those techniques.


#8

Oh yeah, learned that one the hard way. Stared at that for several minutes until it hit me that 0 == false (oops).


#9

In similar cases I do it this way:

this.timeout = typeof n !== "undefined" && typeof n.timer !== "undefined" ? parseInt(n.timer) : 30;

#10

Excellent, works for 0 and a undefined (n or n.timer).

Thanks, I'll make a note of that. I'm sure, I'll run across this again


#11

Just a comment on variable scope. If you are using newer NodeJS versions, you should use let or const instead of var. let ensures that a variable is locally scoped.