Node-RED – Voorbeeld – Save variable to disk
On this page we give an example and some back=information how to store a node-red variable to disc, so that after a shutdown it can retrieve the data back again.
Some guides here:
https://nodered.org/docs/user-guide/context
https://stevesnoderedguide.com/node-red-variables
Example 1 – In a function
To enable disc writing, edit the node-red settings.js file (mostly found in home/pi/.node-red)
Add these lines (they can also be found in the text)
1 2 3 4 5 |
contextStorage: { default: "memoryOnly", memoryOnly: { module: 'memory' }, file: { module: 'localfilesystem' } }, |
Then when you want to store a value from a function you can use for example:
1 2 3 4 |
var count = 25; context.set("count", count, "file"); return msg; |
The value will be written every 30 seconds.
Where is it stored?
Official docs: https://nodered.org/docs/api/context/store/localfilesystem#options
There is a JSON file created with the value in de .node-red/context folder, for example:
.node-red/context/ae043a50.ff6048/44f81811.9a5e08.json
Where the foldername is the Flow ID (ae043a50.ff6048)
And the filename is the Node Id (44f81811.9a5e08)
Contents of the JSON file (with the example above)
1 2 3 |
{ "count": 25 } |
To retrieve the value, use in a fucntion:
1 2 3 |
msg.payload = context.get("count", "file"); return msg; |