• V
 

将文本拆分为每行一条消息

问题

你想要对一段文本的每一行执行操作。例如,你想要在每行的开头添加行号。

解决方案

Split 节点可用于将消息拆分为每行一条消息。它后面可以跟着对文本的各个行进行操作所需的节点,再跟着一个 Join 节点,将它们重新组合成一个文本块。

示例

[{"id":"df6514f0.029748","type":"inject","z":"64133d39.bb0394","name":"inject","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":"","x":110,"y":900,"wires":[["11f53f61.2f7be1"]]},{"id":"11f53f61.2f7be1","type":"template","z":"64133d39.bb0394","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"one\ntwo\nthree\nfour\nfive","x":240,"y":900,"wires":[["760c1d71.c29744"]]},{"id":"760c1d71.c29744","type":"split","z":"64133d39.bb0394","name":"","splt":"\\n","x":190,"y":960,"wires":[["3e427aac.9b9596"]]},{"id":"3e427aac.9b9596","type":"change","z":"64133d39.bb0394","name":"Prepend line number","rules":[{"t":"set","p":"payload","pt":"msg","to":"(parts.index+1) & \": \" & payload","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":360,"y":960,"wires":[["d44d4767.945fd8"]]},{"id":"d44d4767.945fd8","type":"join","z":"64133d39.bb0394","name":"","mode":"auto","build":"string","property":"payload","propertyType":"msg","key":"topic","joiner":"\\n","timeout":"","count":"","x":530,"y":960,"wires":[["bfe3e43b.85fa88"]]},{"id":"bfe3e43b.85fa88","type":"debug","z":"64133d39.bb0394","name":"debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":650,"y":960,"wires":[]}]

讨论

在本例中,InjectTemplate 节点用于注入一个包含多行的文本块。

one
two
three
four
five

Split 节点在传递字符串时的默认行为是将其拆分为每行一条消息。

Change 节点使用 JSONata 表达式修改每个消息的有效负载:(parts.index+1) & ": " & payload - 它使用 msg.parts.index 获取行号并将其前置到现有的 msg.payload

最后,Join 节点将消息重新组合成一个文本块

1: one
2: two
3: three
4: four
5: five