References to external objects

As you probably know, when messages are passed between nodes they are cloned. This allows to duplicate messages to multiple outputs, so that a manipulation of the message in one flow will not affect the other message in a second flow.

Sometimes you may want to have messages with a reference to an external object, that is not a part of the message - so that modifying the external object in one place will change it across all the messages.

Instead of saving the external object inside the message as-is, we save a getter function that returns it.

Warning: This trick is based on the fact that when the "clone" package clones functions, it does not clone their scope. The behavior may change in the future.

[{"id":"a96ab086.56955","type":"inject","name":"","topic":"","payload":"{\"hello\": \"world\"}","payloadType":"none","repeat":"","crontab":"","once":false,"x":125.50000762939453,"y":138.50001907348633,"z":"9edd4545.6122b8","wires":[["149acc4c.eb6534"]]},{"id":"63af3cb5.9c50c4","type":"debug","name":"","active":true,"console":"false","complete":"payload","x":630.5000076293945,"y":205.50001907348633,"z":"9edd4545.6122b8","wires":[]},{"id":"3bcc0d84.c433f2","type":"function","name":"Deref","func":"msg.payload = msg.payload();\nreturn msg;","outputs":1,"x":482.50000762939453,"y":205.50001907348633,"z":"9edd4545.6122b8","wires":[["63af3cb5.9c50c4"]]},{"id":"149acc4c.eb6534","type":"function","name":"create external object","func":"var externalObject = {\"hello\": \"world\"};\nmsg.payload = function() {\n  return externalObject\n};\nreturn msg;\n","outputs":1,"x":225.50000762939453,"y":209.50001907348633,"z":"9edd4545.6122b8","wires":[["2665df56.d99a2","c1dea920.3e2158"]]},{"id":"2665df56.d99a2","type":"delay","name":"","pauseType":"delay","timeout":"5","timeoutUnits":"seconds","rate":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":354.50000762939453,"y":112.50001907348633,"z":"9edd4545.6122b8","wires":[["3bcc0d84.c433f2"]]},{"id":"c1dea920.3e2158","type":"function","name":"manipulate external object","func":"msg.payload().hello = \"lalala\";\nreturn msg;","outputs":1,"x":397.50000762939453,"y":275.5000190734863,"z":"9edd4545.6122b8","wires":[["3bcc0d84.c433f2"]]}]
ozomer

Flow Info

created 2 years, 3 months ago

Node Types

Core
  • debug (x1)
  • delay (x1)
  • function (x3)
  • inject (x1)

Tags

  • getter
  • external-object
  • clone
  • reference
Copy this flow JSON to your clipboard and then import into Node-RED using the Import From > Clipboard (Ctrl-I) menu option