Auri
Auri

Reputation: 13

for loop in function node causes crash in Node-RED application on IBM Bluemix

I'm currently using Node-RED as a cloud-foundry-application on IBM Bluemix. So i'm using the flow editor of Node-RED which is running on a Google Chrome Browser. In my flow, i've a function-node and everytime this one is executed, the app crashes and i've to restart it.

Here is the code of the function-node:

var id_array = context.get('id_array')||[];
var id_index = context.get('id_index')||0;
var first_time_execution = context.get('first_time_execution')||true;
var i;
var sensor_id = msg.payload.sensor_data.sensor_id;

if(first_time_execution){
    id_array[0] = undefined; 
    first_time_execution = false;
    context.set('first_time_execution', first_time_execution);
}

/*for(i = 0; (id_array[i] === undefined) || (i > 256); i++){
    if(sensor_id == id_array[i]){
        msg.payload.array_index = i;

        context.set('id_array', id_array);
        context.set('id_index', id_index);

       return msg;
    }
}*/

id_array[id_index] = sensor_id;
msg.payload.array_index = id_index;

if(id_index > 256){
    id_index = 0;
}else{
    id_index++;
}

context.set('id_array', id_array);
context.set('id_index', id_index);

return msg;

I've located the problem in the for loop between the /* */, because without this section, the app doesn't crash.

What i want to do is: I get a msg object with sensor data from a gateway. Connected to this gateway are several sensors, which have an ID and are sending measurement data to the gateway. To distinguish and store those data, i want to register the ID of every sensor and store it in the conxtext of the node. In the for loop i'm checking if the ID has already been registered.

If anyone knows what could cause this crash, i would be very thankfull.

P.S. I don't know if this is important, but the credential, settings and the flow itself are stored in a cloudantDB.

Upvotes: 1

Views: 922

Answers (1)

chughts
chughts

Reputation: 4747

In a javascript for loop the condition is in essence a while and not an until so for your condition

(id_array[i] === undefined) || (i > 256)

The left side of the or is true when the field is undefined. The right side is true when the iteration has gone beyond 256. Which means that you will be accessing id_array[257] and beyond, and will get an unaccessible memory exception, which unless caught will crash your application.

Upvotes: 1

Related Questions