Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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.

like image 218
Randy435 Avatar asked Sep 19 '14 19:09

Randy435


People also ask

How do you end a NodeJS process?

Method 1: Using ctrl+C key: When running a program of NodeJS in the console, you can close it with ctrl+C directly from the console with changing the code shown below: Method 2: Using process. exit() Function: This function tells Node. js to end the process which is running at the same time with an exit code.

What does Response end do in NodeJS?

end() Function. The res. end() function is used to end the response process. This method actually comes from the Node core, specifically the response.

What is the function of response end listener?

The purpose is to do cleanup based on the http response code that the end handler decided to send, e.g. logging the response code and rollback/commit of a db transaction.

What is request end?

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.


1 Answers

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.
like image 151
Mike S Avatar answered Sep 30 '22 03:09

Mike S