what is res.on() in http request?

Posted on
  • How does the callback in an http request work? Why is there a second callback? I thought the callback supplied with the request would be called when the response was returned, yet this seems to be placing another callback waiting on... something...?

    var http = require("http");
    http.get("http://www.espruino.com", function(res) {
     res.on('data', function(data) {
      console.log(data);
     });
    });
    

    When does res.on() get called?
    Does res.on('data') get called only once per request, or can it be called multiple times, each time with a piece of the data? If the latter is true, how do I know that i've got all the pieces?

    The link in the http docs for more info on the node.js http api is dead - possibly when working this would explain it - but nodemanual.org seems to be down. http://nodemanual.org/latest/nodejs_ref_guide/http.html

    The use case I've got in mind is - I want to fetch a file and evaluate it, and am wondering if I can safely do this, or whether sometimes the data won't be complete, hence the eval will fail.

    var http = require("http");
    http.get("http://master/program.js", function(res) {
     res.on('data', function(data) {
      eval(data);
     });
    });
    
  • Thanks... I'll try and update the docs. Basically:

    • function(res) is called when the connection is established
    • on('data') is called when there's a chunk of data (this almost certainly will be more than once)
    • on('close') is called when the connection closes.

    The HTTP image loader example does this:

      require("http").get("http://www.espruino.com/images/espruino_84_48_1bpp.bmp", function(res) {
        var bmpString = "";
        res.on('data', function(data) { bmpString += data; });
        res.on('close', function() { 
          var img = require("BMPLoader").load(bmpString);
          // ...
        });
      });
    
  • Cool, thanks, just what I was looking for.

  • I've just updated the http docs, and I just tweaked the example above: If you define bmpString in the callback function (rather than outside) then you won't have any problms if you have two concurrent GETs happening at once.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

what is res.on() in http request?

Posted by Avatar for DrAzzy @DrAzzy

Actions