calling nodejs request.end() method before setting up the listeners

In the nodejs docs http://nodejs.org/api/http.html#http_event_connect_1 the example code calls request.end() before setting up the listeners(i.e req.on(...) methods). The example code snipet is shown below.

  var req = http.request(options);
  req.end();

  req.on('connect', function(res, socket, head) {
    console.log('got connected!');

    // make a request over an HTTP tunnel
    socket.write('GET / HTTP/1.1\r\n' +
                 'Host: www.google.com:80\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    socket.on('data', function(chunk) {
      console.log(chunk.toString());
    });
    socket.on('end', function() {
      proxy.close();
    });
  });

If this case doesn't the request ends immediately before the listeners are set and the listeners may never be called at all.

The req.end() call is saying that you're done sending the request body to the server (in this case there's no request body), not that the full request/response cycle is complete. Also, http.request will defer the start of the connection to the server until the next pass through the run loop to give you a chance to setup your listeners.

So, in essence, it's doing something like this:

  1. Create a new request
  2. Tell the request that we're done sending the data we're going to send
  3. Tell the request to let us know when we connect to the server

Next Run Loop Pass

  1. Attempt to connect to the server

After Successful Connection

  1. Send request, etc.