11

I have a node js process that creates a web3 websocket connection, like so:

web3 = new Web3('ws://localhost:7545')

When the process completes, it does not exit, but rather hangs forever with no console output.

Taking at look at what handles the process has outstanding with process._getActiveRequests() and process._getActiveHandles(), I see this:

Socket {
    connecting: false,
    _hadError: false,
    _handle: 
     TCP {
       reading: true,
       owner: [Circular],
       onread: [Function: onread],
       onconnection: null,
       writeQueueSize: 0 },
    <snip>
    _peername: { address: '127.0.0.1', family: 'IPv4', port: 7545 },
    <snip>
}

Looks like web3 is holding a socket open, which makes sense since I never told it to close the connection. Looking through the documentation and googling, it doesn't look like there's a close or end method for the web3 object.

Manually closing the socket allows the process to successfully exit:

web3.currentProvider.connection.close()

Anyone have a more elegant or officially sanctioned solution? It feels funny to me that you have to manually do this rather than have the object destroy itself on process end.

2 Answers 2

2

WebSockets provide a persistent connection between a client and server. This connection has to be manually closed, otherwise the library tries to keep the connection alive.

It feels funny to me that you have to manually do this rather than have the object destroy itself on process end.

The process does not end unless all connections and methods end. Node.js will not close your connection.

You have to close your persistent connections if you want to your process to exit or call process.exit(0).

0

I can't find any reference to this in the docs, but there's a disconnect() method on the providers, so this works:

web3.currentProvider.disconnect();

This is being used all over their code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.