Search code examples
node.jssocketsipcunix-socket

NodeJS net.Socket: `connect` vs `ready` event


I had hard time debugging a problem with my NodeJS' code today.

I have problems when I open two connections to the same unix socket (reasons though); and for unknown reasons, sometimes it works fine throughout; and sometimes I don't get back any data, but connect is fired for only one of them.

I'm still trying to debug, but I deep dived into documentation and faced another question. As NodeJS Docs (12.x LTS) states: (about net.Socket)

# Event: 'connect'
Added in: v0.1.90
Emitted when a socket connection is successfully established. See net.createConnection().

# Event: 'ready'
Added in: v9.11.0
Emitted when a socket is ready to be used. Triggered immediately after 'connect'.

(https://nodejs.org/docs/latest-v12.x/api/net.html)

I wondered if that is where I should look for error:

  • what does immediately mean? Does it mean synchronously? If so, is there any difference between ready and connect?
  • is there any point for one using ready instead of connect for doing after-connection-established/opened tasks?
  • what is the difference between the two?

Thanks!


Solution

  • This event is emitted from net for consistency across different APIs. See the original commit here: https://github.com/nodejs/node/commit/1c8149417a5dec9b2af056f306822b8a22a09706

    It was created to make developers' life easier when working with fs and net code, so that they don't have to remember all the intricate details of a given stream implementation.

    In practice, the Node.js socket code does this:

    self.emit('connect');
    self.emit('ready');