Using the functionGlobalContext

Hi,

This is my first post, so please let me know if I'm doing something wrong.

I am using node-red v1.0.6 on a Raspberry Pi 4 B.

I am currently using a custom node module in my function nodes, imported by using the functionGlobalContext in the settings.js file. the js file is saved in /.node-red/custom_classes/Classes.js.

From the settings.js file:

functionGlobalContext: {
        Classes : require('/home/pi/.node-red/custom_classes/Classes.js')

Here is what I'm currently doing in a function node (simplified):

const Classes = global.get('Classes');

let device1 = new Classes.Device();
let device2 = new Classes.Device();

let devices = [];

devices.push(device1);
devices.push(device2);

global.set("devices",devices,"file")

Then I am using the Device objects in other function nodes like this:

var devices = global.get("devices","file");

for (var device of devices) {
    for (var tag of device.tags) {
       console.log(tag.name);
    }
}

This is working correctly, and i can access all the methods in the Device objects from the function nodes.

The problem is that when I reboot the raspberry pi, I get "TypeError: device.tags is not iterable". I am saving the devices array to file (using contextStorage) so I can see the devices array in the global context menu bar after reboot (see picture), with all field variables, but apparently I can't access the methods.

I don't know how to work this out, so any help with this is appreciated!

image

You cannot persist functions to file storage.

The best you can do rebuild the objects on initialisation (e.g. use an inject set to operate on start up, read your objects in, build new objects, overwrite the context variable)

TBH, you might be better off keeping the data and functionality separate and only store / retrieve the data object.

Alternatively, could pass the global.set or flow.set function to your class instance and execute it inside your class to serialise the internal data. (and same for get() to re-populate an object)

Thanks for the quick reply!

Ok, I was thinking I maybe had to do something like this to make it work.

Thanks for the suggestion, I'll try to do that.

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