No callback on HTTP response.end?

Posted on
  • Is that normal that a function as only parameter of response.end is not called. I was expecting the same behavior as on Node .

    http.createServer(function (req, res) {
          //...
          res.end(function(){
            // never called
            console.log('GET done.');
            digitalWrite(LED2,0);
          });
    }
    

    I don't find the sources of http module. But it seems to always consider first arg as data.

    Is there another way to achieve this?

  • Hmm, I didn't know that was even possible - it feels a bit iffy - for instance if you're trying to serve up a file containing a JS function, if you try and serve up a variable containing the function rather than a variable containing a string representing the function, it'll get executed :s

    I'm pretty sure you can just use the 'close' event though?

    http.createServer(function (req, res) {
          //...
          res.on('close', function() {
            console.log('GET done.');
            digitalWrite(LED2,0);
          });
    }
    

    If you're interested, source of the HTTP module is here - it it's in C.

  • Hmm, I didn't know that was even possible - it feels a bit iffy - for
    instance if you're trying to serve up a file containing a JS function,
    if you try and serve up a variable containing the function rather than
    a variable containing a string representing the function, it'll get
    executed :s

    I'm not sure to understand what you mean. The callback is always the latest of the given arguments. If end(a), a() will be called. If end(a,b), b()... The type does not matter to tell which argument is what.

    I'm pretty sure you can just use the 'close' event though?

    I will try this.

    If you're interested, source of the HTTP module is here - it it's in C.

    Thanks. It will spare me to ask useless questions :)

  • I'm not sure to understand what you mean.

    Just that if you have the following:

    var response = "Hello";
    http.createServer(function (req, res) { res.end(response); });
    

    But you do this:

    response = function() { console.log('Oh no!'); };
    

    Then the behaviour is totally different. It just sounds pretty dangerous - maybe you intended to send the function to the client as a JS file when writing the code, but actually without warning or error it executes it on the server!

  • Well you should never just execute any code coming from outside, that's for sure. You always have to make some sanity check on the received data.
    But I agree that this syntax is kind of dirty and dangerous!

  • res.on('close', fn) works. Thank you @Gordon.

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

No callback on HTTP response.end?

Posted by Avatar for Mr.Peu @Mr.Peu

Actions