What to do when even ChatGPT generated code does'nt work?

I wanted to check all the global variables in order to delete those older than X minutes.
I wrote the test code but unfortunately global.keys() allways returned an empty value, despite the considerable amount or defined ram global variables. Here is my code:

var lapsecs;
var cur;
var w;

node.warn(global.keys());
global.keys().forEach(key => {
    cur = global.get(key);
    lapsecs = (Date.getTime() - cur.last_seen);
    if (lapsecs>10){
        w = key + ' ' + lapsecs.toString();
        node.warn(w);
    }
});

I was so frustrated that I asked to chatGPT to generate the code in such a way:

Give me the code for a function-type node in Node-RED that checks global variables and sees if the “last_seen” attribute is older than 10 seconds than the current time.

I got the following

var now = Date.now();  // otteniamo il tempo attuale in millisecondi

// controlla ogni variabile globale
for (var globalVar in global) {
    // verifica se l'attributo "last_seen" esiste nella variabile globale e se è stato visto più di 10 secondi fa
    if (global.hasOwnProperty(globalVar) && global[globalVar].hasOwnProperty("last_seen") && (now - global[globalVar].last_seen > 10000)) {
        // esegui un'azione (ad esempio, stampa un messaggio di avviso nella console di Node-RED)
        console.log("La variabile globale '" + globalVar + "' non è stata vista da più di 10 secondi!");
    }
}

// restituisci null perché non vogliamo emettere alcun output
return null;

Despite the use of an edge AI tool I got back the same wrong(?) result. So, probably , I’m not more stupid than an AI bot…
I changed the node-red settings.js file in order to allow the global variables to be exposed by global.keys() function.
What can I do to access all the global variables?

1 Like

Love it, I created some functions as well to check websites for changes. Neat tool if you know what you are doing and able to verify :wink:

@Markus: can you see where Is the problem in my code? It should work afaik.

The default global to retrieve is “file” on CORE, to get the ram variable you would use something like this:

global.get("myvar", "ram")

This would fail for any global which doesn’t have the property “last_seen” and would then break the loop. The chatGPT solution handles that, but doesn’t use “global” correctly.

What did you change? This should work by default.

This flow should illustrate how to access all globals:

[{"id":"702a0f18e8b320cb","type":"function","z":"1ae1a884.3eb117","name":"Iterate over globals","func":"var now = Date.now();  // otteniamo il tempo attuale in millisecondi\n\n// This shows they keys you have, uncomment to see this message for debugging:\n// node.error({\n//     'payload': global.keys(),\n// })\n\n// controlla ogni variabile globale\nfor (var globalKey of global.keys()) {\n    let globalVar = global.get(globalKey);\n    // verifica se l'attributo \"last_seen\" esiste nella variabile globale e se è stato visto più di 10 secondi fa\n    if (globalVar && globalVar.hasOwnProperty(\"last_seen\")) {\n        if (isNaN(globalVar.last_seen)) {\n            node.error({\n                'payload': {\n                    'error': 'Last seen NOT a number!',\n                    'last_seen': globalVar.last_seen\n                }\n            });\n        } else if (now - globalVar.last_seen > 10000) {\n            // esegui un'azione (ad esempio, stampa un messaggio di avviso nella console di Node-RED)\n            // console.log(\"La variabile globale '\" + globalKey + \"' non è stata vista da più di 10 secondi!\");\n            node.send({\n                'payload': {\n                    'result': \"La variabile globale '\" + globalKey + \"' non è stata vista da più di 10 secondi!\",\n                    'last_seen': new Date(globalVar.last_seen)\n                }\n            });\n        }\n    }\n}\n\n// restituisci null perché non vogliamo emettere alcun output\nreturn null;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1750,"y":420,"wires":[["cb1b42a8f8480811"]]},{"id":"9f5f19c72b89e76f","type":"inject","z":"1ae1a884.3eb117","name":"Test function","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":1510,"y":420,"wires":[["702a0f18e8b320cb"]]},{"id":"cb1b42a8f8480811","type":"debug","z":"1ae1a884.3eb117","name":"last_seen","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":2000,"y":420,"wires":[]}]
1 Like

That is the response. I have to use globals.keys(“ram”) to access the values. now it works flawlessly.

var lapsecs;
var cur;
const d = new Date();

global.keys("ram").forEach(key => {
    cur = global.get(key,"ram");
    if (cur.last_seen === undefined){
        node.warn(key + ' has no last_seen');
    }else{
        lapsecs = Math.trunc((d.getTime() - cur.last_seen)/1000);
        if (lapsecs > 60) {
            node.warn(key + ' ' + lapsecs.toString());
        }
    }
});

I changed the value of exportGlobalContextKeys from false to true in the settings.js, as I understood it was required in order to let global.keys() to work.

1 Like

exportGlobalContextKeys controls whether the global context keys set via functionGlobalContext are exposed or not.

Any global context properties set in the flow itself will always be returned.

So would not be needed for what you’re doing.

That is true. This property is to mask on/off hardcoded values (that is explicitly declared in settings.js) at starttime if I well understood.
Thank you Markus

1 Like

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