通过上下文存储更新node-red中的文件

时间:2018-01-23 15:51:58

标签: node-red

我已编写代码来更新node-red中的文件,该文件可以按照我的意愿运行。我不太确定它是否可行。当按下注入按钮时,当前值通过上下文存储,读取文件并将存储的数据添加到其中。 (a-)同步性怎么样?如果存储的数据变大怎么办?也许数据还没有存储,但旧的数据写入文件?这有可能吗?我可以通过某种方式使用某种回调函数来解决这个问题吗?

这是节点红色代码:

[{" ID":" ff428878.2bf0d8""类型":"注入"" Z&#34 ;:" 33a0c3f0.5ad66c""名称":"""主题":"",& #34;有效载荷":"""的payloadType":"日期""重复":"&# 34;," crontab的":"""一次":假," X" 140" Y&#34 ;:80,"电线":[[" d97f4731.48f508"]]},{" ID":" aff66bbc.653048&#34 ;, "输入":"提交"," z":" 33a0c3f0.5ad66c","名称":&# 34;""文件名":" examplefile.txt""格式":" UTF8""大块& #34;:假," sendError":假," X" 380" Y":240,"电线":[[ #&34; 82b889ff.4e5f18"]]},{" ID":" 216dc166.5c79be""类型":"文件&# 34;," Z":" 33a0c3f0.5ad66c""名称":"""文件名&#34 ;: " examplefile.txt"" appendNewline":真," createDir":假," overwriteFile":"真&#3 4;," X":900," Y":80,"电线":[]},{" ID":&# 34; 9238c649.dac2e8""类型":"功能"" Z":" 33a0c3f0.5ad66c"&#34 ; name":" merge"," func":" if(msg.topic == \" new \"){\ n context.set(' shortterm',msg.payload); \ n return [null,msg]; \ n} \ n \ nif(msg.topic == \" old \&#34 ;){\ n msg.payload.push(context.get(' shortterm')); \ n返回[msg,null]; \ n} \ n \ n","输出":" 2"" noerr仅":0," X" 611" Y":80,&#34 ;电线":[[" 216dc166.5c79be"],[" aff66bbc.653048"]]},{" ID":" d97f4731 .48f508""类型":"功能"" Z":" 33a0c3f0.5ad66c""名称&# 34;:"标记为新"," func":" msg.topic = \" new \&#34 ;; \ nreturn msg;&#34 ;,"输出":1," noerr仅":0," X" 400" Y":80,"导线":[[" 9238c649.dac2e8"]]},{" ID":" 10b8938f.1cddfc""类型" :"功能"," z":" 33a0c3f0.5ad66c","名称":"标记为旧" ," func":" msg.topic = \" old \&#34 ;; \ nreturn msg;","输出":1, " noerr仅":0," X":810," Y":240,"电线":[[" 9238c649。 dac2e8"]]},{" ID":" 82b889ff.4e5f18""类型":"功能"&#34 ; z":" 33a0c3f0.5ad66c"," name":" JSON解析"," func":" if (msg.payload){\ n msg.payload = JSON.parse(msg.payload); \ n} \ n \ n返回消息;","输出":1," noerr仅":0," X":610," Y":240,"电线":[[" 10b8938f.1cddfc" ]]},{" ID":" 7572637c.0a25ac""类型":"文件"" Z&#34 ;:" 33a0c3f0.5ad66c""名称":"""文件名":" examplefile.txt" " appendNewline":真," createDir":假," overwriteFile":"真"" X&#34 ;: 510," Y" 480"电线":[]},{" ID":" 1f6b904 3.ff153""类型":"注入"" Z":" 33a0c3f0.5ad66c""名称& #34;:"""主题":"""有效载荷":" []" "的payloadType":" JSON""重复":""" crontab的":" 25 22 * * *","一次":false," x":210," y":460,"电线&#34 ;:[[" 7572637c.0a25ac"]]}]

2 个答案:

答案 0 :(得分:1)

如果您使用单个流程来读取文件,则在读取文件之前,流程中的下一步将不会发生。

所以你的流程太复杂了。

inject->read file->json node (if the file content is json)->
  function node->write file

函数节点:

  1. 获取上下文变量(如果不存在,则创建一个空变量)
  2. 将文件数据与上下文合并
  3. 写入上下文变量
  4. msg.payload更改为更新的内容
  5. return msg

答案 1 :(得分:0)

使用Node-Red 19.0+进行持久文件存储的另一个新选项是内置的“上下文存储”。

这里有一篇很好的关于如何使用上下文存储滚动的文章:

https://discourse.nodered.org/t/a-guide-to-understanding-persistent-context/4115

基本操作是使用contextStorage设置更新 〜/ .node-red / settings.js 文件:

contextStorage: { default : { module: "memory" }, fileStore: { module: "localfilesystem"} },

您可以在其中引用流程:

flow.set("jsObj", "Hello there!", "fileStore");

要取回数据:

flow.get("jsObj", "fileStore")

此时,您可以在 〜/ .node-red / context / 文件夹中看到保存的文件。

上面的链接文章应该能够回答任何其他问题。