TypeError: Cannot read property '0' of undefined

I am getting a type error - Cannot read property '0' of undefined in my function node. I am not sure what is exactly the mistake. I have attached my flow. Can someone suggest me what should i do to solve the error. I am quite new to Node red.

[{"id":"678e3899.0cdf4","type":"inject","z":"99a7958.4ae3d68","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":200,"y":100,"wires":[["c9bb7218.572258"]]},{"id":"3bb10800.6e3de","type":"file in","z":"99a7958.4ae3d68","name":"","filename":"C:\\Users\\Public\\Varun\\PreHeating_2019-09-13_19-23-41.csv","format":"utf8","chunk":false,"sendError":false,"x":350,"y":340,"wires":[["d4fd98ff.6fd27"]]},{"id":"a4dc0c6d.b5db38","type":"function","z":"99a7958.4ae3d68","name":"Selecting the file","func":"\nmsg.filename = \"\\\\\\\\C:\\\\Users\\\\Public\\\\Varun\\\\PreHeating_2019-09-13_19-23-41.csv\";\nreturn msg;\n","outputs":1,"noerr":0,"x":630,"y":220,"wires":[["3bb10800.6e3de"]]},{"id":"3685a12.f68965e","type":"function","z":"99a7958.4ae3d68","name":"Calculate average ","func":"const inputArray = new Array (msg.payload.length);\n  for (var n = 0 ; n < inputArray.length ; n++) {\n    inputArray[n] = Object.values(msg.payload[n]);\n  }\n\n  // width and height of heating fields in pixels\n  // dependant on distance between camera and object\n\n  const FIELD_WIDTH = msg.config[0].col2;// 4;\n  const FIELD_HEIGTH = msg.config[1].col2;// 4;\n\n  // Width resolution of Images\n\n  const RES_WIDTH = msg.config[2].col2;// 100;\n\n  // # of heating fields to calculate\n\n  const FIELDS_HORIZONTAL = msg.config[3].col2;// 6;\n\n  // because of zig-zag recording of camera 1 to generate same layouts.\n\n  const FIELDS_VERTICAL = msg.config[4].col2;// 28;\n\n  // first field starts half the field amount in length from middle of the image.\n\n  // const HEATING_FIELD_START_HORIZONTAL = RES_WIDTH/2 -  msg.config[3].col2 *msg.config[0].col2;\n  const HEATING_FIELD_START_HORIZONTAL = 0;\n\n  // Detect start of Fields// emperic values maybe?\n\n  var HEATING_FIELD_START_DETECTION = detectStartHeating(inputArray);\n  var HEATING_FIELD_END_DETECTION = detectEndHeating(inputArray);\n  // var HEATING_FIELD_START_VERTICAL = (HEATING_FIELD_END_DETECTION - HEATING_FIELD_START_DETECTION )/ 2 + HEATING_FIELD_START_DETECTION - msg.config[4].col2/2 *  msg.config[1].col2;\n  var HEATING_FIELD_START_VERTICAL =0;\n\n  // Creating an empty output Array with the set no fields\n\n  var outputArray = new Array (FIELDS_VERTICAL);\n  for (var k = 0 ; k< outputArray.length ; k++) {\n    outputArray[k] = new Array (FIELDS_HORIZONTAL);\n    for ( var l = 0; l< outputArray[k].length; l++) {\n      outputArray[k][l] = 0;\n    }\n  }\n\n  var tmp2 = 0;\n\n  // loop through the fields\n\n  for (var v = 0 ; v < FIELDS_VERTICAL ; v++) {\n    for ( var h = 0; h < FIELDS_HORIZONTAL ; h++) {\n   \n      //calculate median of each field\n      var tmp = 0 ;\n      for ( var y = HEATING_FIELD_START_VERTICAL + v *  FIELD_HEIGTH ; y < HEATING_FIELD_START_VERTICAL + v *  FIELD_HEIGTH +  FIELD_HEIGTH; y++) {\n        for (var  x = HEATING_FIELD_START_HORIZONTAL + h *FIELD_WIDTH; x < HEATING_FIELD_START_HORIZONTAL + h * FIELD_WIDTH + FIELD_WIDTH; x++) {\n          tmp += parseFloat(inputArray[y][x]);\n        }\n      }\n          \n      // round to 2 decimals\n      tmp = tmp / (FIELD_WIDTH * FIELD_HEIGTH)\n        \n      // no of decimal digits\n      \n      tmp = Math.round(tmp);\n      outputArray[v][h] = tmp;\n\t\t}\n  }\n  \n  // Create an empty array to insert the data\n  // The desired output has 7 rows\n  var newOutput = new Array (7);\n  for (var k = 0 ; k< newOutput.length ; k++) {\n    // Every row contains as much elements as the total number of fields\n    newOutput[k] = new Array ( FIELDS_HORIZONTAL* FIELDS_VERTICAL);\n    for ( var l = 0; l< newOutput[k].length; l++) {\n      newOutput[k][l] = 0;\n    }\n  }\n\n  // Map the current result to the format desired\n  // 7 rows were\n  // row0 PixelName\n  // row1 Width\n  // row2 Height\n  // row3 X\n  // row4 Y\n  // row5 Average\n  // row6 Consecutive pixel name\n  let firstRowIndex = 0;\n  for (let rowIndex = 0; rowIndex < outputArray.length; rowIndex++) {\n    const row = outputArray[rowIndex];\n    for (let colIndex = 0; colIndex < row.length; colIndex++) {\n      const col = row[colIndex];\n      // Determine the name\n      const pixelName = `${getLettherForRowNumber(rowIndex)}${colIndex}`;\n      newOutput[0][firstRowIndex] = pixelName;\n      newOutput[1][firstRowIndex] = 100; // Width\n      newOutput[2][firstRowIndex] = 100; // Height\n      newOutput[3][firstRowIndex] = colIndex * 100; // X\n      newOutput[4][firstRowIndex] = rowIndex * 100; // Y\n      newOutput[5][firstRowIndex] = col; // Average\n      // Determine the name 2\n      const pixelName2 = `a${firstRowIndex}`;\n      newOutput[6][firstRowIndex] = pixelName2;\n      firstRowIndex++;\n    }\n  }\n\t\n\tmsg.payload = newOutput;\n\t\n  return msg;\n\n\t\nfunction detectStartHeating(inputArray) {\n\t \n\t// Haet difference from cool row to first heated row, how much hotter does the first heated row to be ?\n    \n  const THRESHOLD = 5;\n\n  var hotRow =  0 ;\n  var currentRowAverage = calcRowAverage(inputArray, hotRow);\n  hotRow++;\n      \n  var nextRowAverage = calcRowAverage(inputArray,hotRow);\n  while( currentRowAverage + THRESHOLD > nextRowAverage && currentRowAverage > -1 && nextRowAverage > -1) {\n\n    currentRowAverage = nextRowAverage;\n    hotRow++;\n    nextRowAverage =  calcRowAverage(inputArray,hotRow);\n  }\n    if (nextRowAverage == -1 || currentRowAverage == -1) {\n      return 0;\n    } else {\n      return hotRow;\n    }\n  }\n\nfunction  detectEndHeating(inputArray) {\n // heat difference from cool row to first heated row , how much hotter does the first heated row have to on average?\n \n   const THRESHOLD =  40;\n   var hotRow = inputArray.length - 1;\n   var currentRowAverage = calcRowAverage(inputArray, hotRow);\n   hotRow--;\n\n    var prevRowAverage =  calcRowAverage(inputArray,hotRow);\n\n    while ( currentRowAverage + THRESHOLD > prevRowAverage && currentRowAverage > -1 && prevRowAverage > -1 && hotRow>0) {\n         currentRowAverage = prevRowAverage;\n         hotRow--;\n         prevRowAverage = calcRowAverage(inputArray,hotRow);\n \n         }\n         if( prevRowAverage == -2 || currentRowAverage == -1) {\n             return 0 ;\n         }\n\n          else\n         {\n           return hotRow;\n       }\n   }\n   \nfunction calcRowAverage(inputArray,row) {\n     var res = 0;\n     if (inputArray.length < row) {\n         return -1;\n     }\n\n\n     for (var g = 0; g< inputArray[row].length; g++) {\n         res += inputArray[row][g];\n       }\n      return res/inputArray[row].length;\n}\t  \n\nfunction getLettherForRowNumber(rowNumber) {\n  // ASCII code for 'a' is 97, 122 for 'z'\n  if (rowNumber < 26) {\n    return String.fromCharCode(97 + rowNumber);\n  } else {\n    const asciiFirstLetter = Math.round(rowNumber / 25) - 1;\n    const mod = rowNumber % 25 - 1;\n    const firstLetter = String.fromCharCode(97 + asciiFirstLetter);\n    const secondLetter = String.fromCharCode(97 + mod);\n    return `${firstLetter}${secondLetter}`;\n  }\n}","outputs":1,"noerr":0,"x":290,"y":480,"wires":[["31a3b225.c03346"]]},{"id":"31a3b225.c03346","type":"debug","z":"99a7958.4ae3d68","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":590,"y":480,"wires":[]},{"id":"d4fd98ff.6fd27","type":"csv","z":"99a7958.4ae3d68","name":"ReadCSV","sep":";","hdrin":"","hdrout":"","multi":"mult","ret":"\\n","temp":"","skip":"0","x":760,"y":340,"wires":[["3685a12.f68965e"]]},{"id":"c9bb7218.572258","type":"file in","z":"99a7958.4ae3d68","name":"","filename":"C:\\Users\\Public\\Varun\\config.csv","format":"utf8","chunk":false,"sendError":false,"x":500,"y":100,"wires":[["92838f8d.6e6308"]]},{"id":"a0970e0b.a00a2","type":"change","z":"99a7958.4ae3d68","name":"","rules":[{"t":"move","p":"payload","pt":"msg","to":"config\t","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":350,"y":220,"wires":[["a4dc0c6d.b5db38"]]},{"id":"92838f8d.6e6308","type":"csv","z":"99a7958.4ae3d68","name":"ReadCSV","sep":";","hdrin":"","hdrout":"","multi":"mult","ret":"\\n","temp":"","skip":"0","x":120,"y":220,"wires":[["a0970e0b.a00a2"]]}]

Hi @varun

can you help narrow it down a bit? Which Function node is reporting the error? have you tried adding some debug (for example node.warn statements) to identify which line in the Function is hitting that error?

Hi , The calculate Average function node is giving the error. No i havent added any debug node as of now.

In the function node , I am reading a csv file which has the configurations. Then i am moving it to msg.config. And then the main data is being read from another csv file. I am getting an error when i am accessing the variable from the config.csv file.

In your function add some debugging code to display where you are in the code and dump variables to the debug sidebar. You can use
node.warn("debug01 - var g="+g);
which will shoy you at that point in your function node, where you are and what variable g contains.

@zenofmud where should i place that line of code in the function node? Is it after the return msg or at the beginning of the code ?

put it where it makes the best sense. if you put it after the return msg it will never be run.

put a line like that in the function where ever you need to see what is going on at that point in the code. For example, if you have an it statement you might want to put one befrore the if one after.

@zenofmud I have a function node where data needs to be read from two csv files. I read the data from the first csv node and then used a change node to move the ouput to msg.config. Then when the access the variables in the function node. When i am doing it this way I am getting the error - RangeError: Invalid array length. But If I hardcode the values, I am getting the output perfectly.

@zenofmud I checked and saw that the variables are being read perfectly from the csv file, but still getting the error.

If the error is Cannot read property '0' of undefined then something is wrong with your code in the function. With out knowing what the data going inito the function node is, I can't tell you what is happening.

  1. Does the error show a line number?
  2. have you put in the node.warn's n the function node and displayed every variable you use?

@zenofmud No, now the error has changed to RangeError: Invalid array length. The error doesnt show any any line. Yes, I use the node.warn for all the 4 variables and they were being read perfectly.

Without you providing the data going into the function node, there is no way for me to tell what is going wrong.

@zenofmud the data file is too big, I am unable to upload here.

You don't need to upload the entire file. You should be able to put a debug node on the output of the node feeding the function node and find the chuck of data that is triggering the issue.

You should be able to then add an insert node (you might need a change node too) to create a msg that duplicate what is coming from the rest of the flow. That fed into the function node should replicate the error making it easy to share wth someone to help solve your issue.

@zenofmud I placed a debug node to the input of the function node and the input is as expected to the function node. No errors here. There is an error inside the function node, I think i got the part of the code where error is generated but I am unable to understand the reason for it because the same part of the code is working fine if variables are hard coded. And the variables are bring read from the csv file also as wanted.

Can you provide even a basic sample of the data your function is meant to be handling. Otherwise we have no idea what you are doing with this code, nor why it may hit any error.

Your Function node is almost 200 lines long. I can see dozens of places where it accesses an array - which would cause the error you are seeing if that array is undefined. Have you added node.warn() statements next to every line that does an array access to confirm the array actually exists?

We cannot tell you why your code is hitting that error. All we can do is try to point you at the steps needed to debug it for yourself.

Sorry, but without isolating the data that is causeing the problem I can't help you.

These are the snaps of the input csv file and the input to the function node. The input to the function node ias expected as seen.

@knolleary I added the node.warn and found that

var outputArray = new Array (FIELDS_VERTICAL);
for (var k = 0 ; k< outputArray.length ; k++) {
outputArray[k] = new Array (FIELDS_HORIZONTAL);
for (var l = 0; l< outputArray[k].length; l++){
outputArray[k][l] = 0;

this part is not giving the output as expected and an error is getting generated.