Sending message when nodes are connected

Hello,
I have created custom nodes in node red by reading the documentation. I have a query regarding sending messages between nodes without using inject node. Specifically, I want to know if there is any way to send messages from node A to node B when output port of node A is connected to input port of node B. Any leads on this will be much appreciated.

From the docs:

Sending messages

If the node sits at the start of the flow and produces messages in response to external events, it should use the send function on the Node object:

var msg = { payload:"hi" }
this.send(msg);

Thanks for the reply. I understood how to send message by calling this.send(msg) but I'm unable to figure out how to send message as soon as two nodes are connected without using inject node.

Ah, you want to trigger on the action of a wire being applied. I see.

Ok, I think this it possible but not simple.

Since a node is essentially destroyed and recreated when you deploy a change, you would have to keep a reference to the wires a node previously had and the wires it has now. Any new wires found, you can call node.receive against those particular nodes.

Alternatively, if it is ok for ALL connect nodes to receive a message upon updating the connections, then a simple this.send upon node instantiation would be simplest.

Can I ask why you want to do this? It is an odd request and there may be a better approach?

1 Like

let me check this and get back to you soon.

I thought about it and what works for me is triggering the message flow just after deploying the flow but without having explicit inject node.

As the flow connecting the 2 nodes gets reloaded when deployed, you can add a send function in the function that you pass to the RED.nodes.registerType call.

Just make sure that you don't call send until after the line that says RED.nodes.createNode(this, config) as that is when you get the fully formed this object.

RED.nodes.createNode(this, config)
this.send({payload: "Hi, I'm deployed"})

You probably want to filter out such messages in your node b though.

Ideally, nodes should be pretty stateless and should not need to know anything about their upstream connections so if you really must use it, do so sparingly because it is not standard and may well confuse flow authors.

Another way to achieve this without having to worry about where those messages are going would be to create/use custom events.

1 Like

I will try this. Thanks for the detailed reply.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.