Skip to content

Instantly share code, notes, and snippets.

@eveiga
Created April 2, 2013 17:01
Show Gist options
  • Select an option

  • Save eveiga/5293995 to your computer and use it in GitHub Desktop.

Select an option

Save eveiga/5293995 to your computer and use it in GitHub Desktop.
var http = require('http');
var server = http.createServer();
server.listen(8000);
server.on('request', function(req, res) {
http.get("http://google.com/index.html", function(response) {
req.on("end", function() {
console.log("ENDED");
});
});
});
@eveiga

eveiga commented Apr 2, 2013

Copy link
Copy Markdown
Author

console.log is never called

@danmilon

danmilon commented Apr 2, 2013

Copy link
Copy Markdown

The end listener is attached too late. The event has already fired.

This ensures that the handler is attached.

var http = require('http');

var server = http.createServer();

server.listen(8000);

server.on('request', function(req, res) {

  req.on("end", function () {
    console.log("ENDED");
  })

  http.get("http://google.com/index.html", function(response) {
    console.log(response.statusCode);
  });
});

@isaacs

isaacs commented Apr 7, 2013

Copy link
Copy Markdown

In v0.10, this is quite different!

// works on v0.10, not on v0.8
var http = require('http');

var server = http.createServer();

server.listen(8000);

server.on('request', function(req, res) {
  http.get("http://google.com/index.html", function(response) {
    req.resume()
    response.pipe(res)
    req.on("end", function() {
      console.log("ENDED");
    });
  });
});

Because stream 'end' doesn't happen until you consume the request, it actually hasn't happened yet.

So, instead of missing the 'end' like you would on v0.8, it's hanging waiting for you to consume the stream, because it starts out paused until you consume it.

@eveiga

eveiga commented Apr 9, 2013

Copy link
Copy Markdown
Author

Nice to know Isaacs. Thanks for the tip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment