前言
- node-red一共有三种变量
- context/flow/global
三种变量的使用请参考下列教程
node-red教程 5.4 context global与函数节点的其它功能
为何需要持久化存储变量
- node-red变量都存储在内存中,当涉及到需要长时间存储的变量就会蒙圈
修改settings.js
修改/config/node-red/settings.js在末尾添加下面代码,注意需要添加逗号与之前的配置隔开,
contextStorage: {
store: { module: "localfilesystem"},
default: { module: "memory" }
}
重启node-red
持久化存储变量演示
将一个时间戳存储为持久化变量的流程
[{"id":"194cc8b7.c747d7","type":"function","z":"6fddb7c0.6e1238","name":"获取当前时间戳","func":"var now = new Date();\nvar timestamp = Date.parse(new Date());\nmsg.timestamp = timestamp;\nreturn msg","outputs":1,"noerr":0,"x":560,"y":400,"wires":[["33d327f2.612d98"]]},{"id":"33d327f2.612d98","type":"moment","z":"6fddb7c0.6e1238","name":"","topic":"","input":"timestamp","inputType":"msg","inTz":"Asia/Shanghai","adjAmount":0,"adjType":"days","adjDir":"add","format":"YYYY-MM-DD HH:mm","locale":"C","output":"time","outputType":"msg","outTz":"Asia/Shanghai","x":800,"y":400,"wires":[["c64f0690.f36dd8"]]},{"id":"c64f0690.f36dd8","type":"function","z":"6fddb7c0.6e1238","name":"记录内容","func":"msg.payload = {};\nmsg.payload = msg.time;\nreturn msg;","outputs":1,"noerr":0,"x":1020,"y":400,"wires":[["af66ec83.b4baf"]]},{"id":"39ec4955.dfcc36","type":"inject","z":"6fddb7c0.6e1238","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":340,"y":400,"wires":[["194cc8b7.c747d7"]]},{"id":"af66ec83.b4baf","type":"change","z":"6fddb7c0.6e1238","name":"","rules":[{"t":"move","p":"timestamp","pt":"msg","to":"#store):pen_door_time","tot":"global"}],"action":"","property":"","from":"","to":"","reg":false,"x":1220,"y":400,"wires":[["6938cf5a.1cd1e"]]},{"id":"6938cf5a.1cd1e","type":"debug","z":"6fddb7c0.6e1238","name":"调式信息","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1420,"y":400,"wires":[]}]
查看刚刚存的持久化变量,点击刷新
读取持久化变量演示
- 持久化存储的变量与存储在内存的变量是两个变量,即使它们名称完全一样
- 读取持久化变量的时候,需声明变量类型,否则会优先读取内存变量,即使这个变量不存在
[{"id":"17b92e08.db1f12","type":"inject","z":"6fddb7c0.6e1238","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":620,"y":540,"wires":[["ce9d5ed6.2510a"]]},{"id":"ce9d5ed6.2510a","type":"function","z":"6fddb7c0.6e1238","name":"读取开门时间","func":"var message = global.get('open_door_time', \"store\");\n\nmsg.payload = {};\nmsg.payload.data = {\"message\":message,\"miai_num\":\"0\"};\nreturn msg;\n","outputs":1,"noerr":0,"x":800,"y":560,"wires":[["5f7fa373.528d2c"]]},{"id":"5f7fa373.528d2c","type":"debug","z":"6fddb7c0.6e1238","name":"调式信息","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1000,"y":560,"wires":[]}]
持久化存储的秘密
存成文件了