Stopping node when removed

I am writing a node to monitor a socket with a custom protocol. It works fine and I had to setup a setInterval to catch random disconnections and re-connect, triggered by the 'close' event.

Now, if I remove the node from my workspace and deploy changes, I see that the node is still working in the background, trying to connect to the server. In which function I can stop the timer when the node is removed from the workspace?

Covered in the docs here: JavaScript file : Node-RED

Hi Nick,
yes I am working with that doc. My problem is that when I receive a "close" (this.on('close')) I need to keep the timer running to retry a connection. I I stop it in that function, the node will definitely close at first error.

If you receive a close event on the node, that means the node is being stopped and you must tidy up all of its resources. You absolutely should not be reconnecting to a server in response.

Are you mixing up the close event of the node wit the close event of whatever connection you have created?

I am clearing the resource before trying to re-instantiate:


      node.client.on('close', function(removed, done) {
        if (removed)  {
          node.error('IP connection closed')
         node.client.destroy()
        } else {
          instantiateClient()
        }
      })

What exactly is node.client?

As I thought, it looks like you are confusing the close event of your network client with the close event of the node.

The removed argument only exists for the close event of the node. But your code looks like to you are trying to handle when your network client loses its connection - which is an entirely different close event.

Yes, I am sure I am mixing up things...

node.client = new net.Socket()

it's a socket.

So, to answer your original question, you need to register a handler for the close event on the node object itself.

In that handler you can close any connections and clear any timers you've created.

1 Like

Thanks for your patience!

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