Search code examples
javascriptnode.jsnode-red

Multiple inputs in function / node-red


OS is Windows 10 / Node-Red Version is 1.0.3 / node.js is v12.14.0

I'm trying to handle multiple msg.payload.subobjects to a function node. But when doing so I always get the error ""TypeError: Cannot read property '0' of undefined" ".

The nodes are providing the correct data (tested in debug nodes). But passing them into a function returns the error.

Is it possible to handle two inputs like that to a function? Cause they both use the msg.payload object?

Here's the prepared version for testing:

[ 
   { 
      "id":"894fec71.7d972",
      "type":"function",
      "z":"dd09b1ba.0e51e",
      "name":"Weather Prediction",
      "func":"var wBees = 0;\nvar wActually = msg.payload.newWt;\n\nvar c0 = msg.payload.data[0].CO2;\nvar c1 = msg.payload.data[1].CO2;\nvar c2 = msg.payload.data[2].CO2;\n\n//wActually.localeCompare(\"rain\") === false\nif(wActually === \"rain\"){\n    wActually = \"good\";\n}else{\n    wActually = \"other\";\n}\n\n//c0, c1, c2 --- 2pm, 10pm, 6am\n  var day = c1-c0;\n  var night = c1-c2;\n\n// Checks proportion\n  if(night > day){\n    // bad weather\n\twBees = \"other\";\n  }else{\n    // good weather\n\twBees = \"good\";\n  }\n\n// Evaluation\nif(wBees == wActually){\n    msg.payload.weatherPredict = \"Correct\" + \" || Current: \" + msg.payload.weather;\n\treturn msg;\n}else{\n\tmsg.payload.weatherPredict = \"Incorrect\" + \" || Current: \" + msg.payload.weather;\n\treturn msg;\n}",
      "outputs":1,
      "noerr":0,
      "x":830,
      "y":360,
      "wires":[ 
         [ 
            "3ee84278.8a86de"
         ]
      ]
   }
]

Solution

  • The problem is that your Weather Prediction function node is receiving 2 separate messages, with different structures. When you split the flow you end up with a copy of the message passing down each branch. They do not get automatically merged when you wire them both into the function node.

    You are trying to access parts of both new messages in the function node. If you need both messages to do that work you will need to insert a join node before the function node, set to wait for 2 messages and to merge the msg.payload values