Best way to save variables across node-red restarts?

Dear Node-redders (are you called like that?)

Just wanted to ask what the best way is to preserve a variable and it's state defined in the .js file of a node. Got some websocket listeners I want to start listening for them again after node-red restarts. How can I do that?

Thank You
Hansi

Hi @hansimeister

If this is outside the basic context of a Nodes config, just use your own mechanism,
and you need it to be accessed only by your module - just roll your own mechanisms - at least that's what I do.

Create a folder if it does not exist.

module.exports = function(RED) {
    function Init(config) {
        ....
        const stateDir = path.join(RED.settings.userDir, 'super-node-state')
        if (!fs.existsSync(stateDir)) {
            fs.mkdirSync(stateDir)
        }
    }
}

Store JSON files in there and read/write/parse them whenever you need, such as checking if there is a state you can use during start up :wink:

Many ways, but this is what I do, as the state objects I need to save/read are very complex and some do not use JSON at all.

EDIT

There is also the Node Context its self (but I don't use it)
https://nodered.org/docs/creating-nodes/context

var nodeContext = this.context();

you need to make sure the Users Node RED is set to use localfilesystem (I think) if you want the values to survive a reboot/restart - again I think, I just use my own mech that I have full control over

https://nodered.org/docs/api/context

Certainly use your own if you don't need/want users of the node to have control. If you do want them to have control, you can use Node-RED's own context methods. I do that, for example, in UIBUILDER's cache node which lets users have full control over whether they want to persist the cache or even make it available to other nodes.

1 Like

In the past, others have suggested using an MQTT broker (i.e. mosquito) that supports "retained messages" -- so when an mqtt in node connects to a topic it receives the last message that was sent to that topic.

I have not tried this myself, but it sounds pretty elegant and bullet-proof. Searching this forum for "mqtt retain context" yields many interesting threads, like this one: Access to mqtt retained messages

Edit: in my pre-caffeine state, I failed to notice the category is "Developing Nodes" -- so this is probably not relevant to what you are doing

:upside_down_face:

I like "node-reddites" -- sounds like "Luddites" that have discovered a simple tool for building everything without needing to embrace more complex emerging technologies... ;*)