• In this puzzle, my goal is to issue an HTTP GET request and when the complete response has arrived, process it.

    Looking at the APIs, I see:

    http.get(options, function(response) {
       // handle response here
    });
    

    In the response handler, I am given an object of type httpCRs (I believe). However, if I try and print:

    response.available()
    

    I am returned a value of 0. I figured that was ok, because at this point, in execution, data had not yet arrived and there was indeed none available.

    So I figured that I could code up the following:

    response.on("close", function() {
       print("Available = " + response.available());
    });
    

    However something seems to be wrong here. The "close" event function is not being called. By sheer luck, I found that if I coded:

    response.on("data", function() {
       print("We have received some data");
    });
    response.on("close", function() {
       print("Available = " + response.available());
    });
    

    I then find that the code event callback is being invoked ... but of course, I have consumed my data.

    So it seems that if I code a response.on("close"...) without a response.on("data"...) the close callback is not being invoked.

    Am I missing a concept here?

  • The client does not close an HTTP connection after sending the request. Specially not with HTTP 1.1. You have to check whether there's a Content-Length header and if there is, read that number of bytes from the socket as payload. (If the encoding is chunked you have to do the equivalent using the chunk length prefixes.)
    If the there is no Content-Length header or the value is zero then you've reached the end of the request when you see \r\n\r\n.

About

Avatar for tve @tve started