Skip to content

Instantly share code, notes, and snippets.

@eveiga
Created April 2, 2013 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eveiga/5293995 to your computer and use it in GitHub Desktop.
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
Copy link
Author

eveiga commented Apr 2, 2013

console.log is never called

@danmilon
Copy link

danmilon commented Apr 2, 2013

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
Copy link

isaacs commented Apr 7, 2013

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
Copy link
Author

eveiga commented Apr 9, 2013

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