Made my Node-RED crash by working with global arrays

I dig around in the forum here, copy pasted some array things and mixed it up with my own knowledge - I thought I do understand :laughing:.
Node-RED crashed some parts of UIBUILDER (clearly my mistake) - now I know more about stop/start/safemode, had to ga back to my .flows.backup.js (found the better solution later)
To prevent this for the future I decided to ask:

I get messages from the windows of my house, like "window livingroom, true" ...
I tried to store them in a global array global.set("housewindowlist").

I do use a function node with some outputs

  • one for sending updates to UIBUILDER (working)
  • one should output the number of open windows (I know hw to do that)
  • one should create the windowlist (a global array - to use it everywhere around)

What would be the "right" way to do it without breaking Node-RED or UIBUILDER

my steps in logic:

  • define an empty array
  • get my message and check if the name of the window is in the array
  • if no - add the name and the status { "name": "windowXY", "status":"open" }
  • if yes - manipulate the entry

(though about getting the global array in the function, paste it in a local, work with the local and if ready overwrite the global?)

I could create a switch case with all known windows easyly, but as I am thinking of extending the window sensors I would love to have a dynamic list, which would last fo some time.

I hope I did not write to much about my mission, but as I was not able to transfer the existing array examples to my needs I am aware I still have to learn a lot more :smiley: for Node-RED

best regards

Not sure I've fully understood your needs but I would personally use an object rather than an array for the window list - simply because it is much easier to access via a key.

// Grab the global var or create a new object if it doesn't exist
const housewindowlist= global.get('housewindowlist') ?? {}

if (msg.windowid) {
  // here you can either see if it already exists but this is only needed if
  // you need to add data from outside the incoming msg
  //const thisWindow = mywindows[msg.windowid]
  //if (!thisWindow) {
    // create the window object
  // If everything is in the msg, you can simply always overwrite - no need to mess around
  mywindows[msg.windowid] = msg.payload

// Don't forget to save the updates
global.set('housewindowlist', housewindowlist)

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.