Sending a message upon startup in a custom node

If you need to send message when your node is initialized, then do it in your constructor with process.nextTick or some other delay mechanism. this works. I just tried it with my custom node.

// send yourself a message
process.nextTick(() => {
    this.emit('input', { payload: 'test input'});
});

// send the next node a message
process.nextTick(() => {
    this.send({ payload: 'test input 2'});
});
2 Likes

Oops! Misread, sorry. Thanks for the clarification and of course you are correct.

Just did a quick test and added this to my nodeInstance function after RED.nodes.createNode(this, config) so that the this object was correctly initialised.

    RED.events.on('flows:started', (data) => {
        console.log('test1', Object.keys(this))
        this.send({topic:'uibuilder-hello', payload: 'hello!'})
    })

I get a log output for each instance of uibuilder loaded into my flow of course but still nothing gets sent so obviously still too early. It also generates a maxListeners warning though that is probably a red herring.

But If I put this in its place:

    setTimeout(() => {
        console.log('test1', Object.keys(this))
        this.send({topic: 'uibuilder-hello', payload: 'hello!'})
    }, 100)

It works as expected (a message sent for each instance of the node in my flows).

You can't put it any earlier in the process though as you don't have a send function except on the initialised node instance - as far as I am aware anyway.

So you should add a flag if you only want a single output - then the first instance of the node would send the msg and the others would be blocked.

1 Like

You should probably use ...

node.receive({payload: 'test input'})

... as it will sanitise the msg (and add a msgid)

1 Like

i was basing my example on the core inject node and how it does it. Although, it uses a setTimeout instead of nextTick and sends itself an empty object. https://github.com/node-red/node-red/blob/master/packages/node_modules/%40node-red/nodes/core/common/20-inject.js#L90

Thanks. i will look into that. I have not seen or used that yet.

1 Like

Do you know where that is defined in the Node-RED code Steve?

@TotallyInformation here node-red/Node.js at 67dd7e30faf1a6fca07f5b745de75f4ad3036ce4 Ā· node-red/node-red Ā· GitHub

It ensures there's a _msgid and then emits the input event.

Either approach is entirely valid.

@kevinGodell the problem using nextTick is that it assumes all nodes start synchronously. If anything has to do any async work then it could get scheduled after nextTick.

Whilst the setTimeout approach isnt the most elegant, it is pretty tried and tested with the Inject node.

2 Likes

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