Maxmengt Maxmengt -4 years ago 58
Javascript Question

When did server add listener to request in Node.js?

var http = require("http");

http.createServer(function(request, response) {
request.addListener("data", function(postDataChunk) {
// some code here
});

request.addListener("end", function() {
// some code here
});
}).listen(8888);


As I know, in node, the anonymous function would execute when server received request. But in the sample code, the function would add listener to request which had received by server. However, it really works.

And my question is why it works. When did server add listener to request in node?

Answer Source

It's not entirely clear to me what exactly which part of the process you're asking for help understand, but here's how your code works.

  1. http.createServer() creates a server and the callback function you pass it is automatically registered as an event handler for the request event.

  2. The request event calls it's callback with two arguments, the request and response objects. The request object is of type http.IncomingMessage which implements the readable stream interface.

  3. When the request callback is call, it executes request.addListener('data', ...) and this adds a listener for incoming data on the readable stream in the request argument.

  4. So, as soon as data is available on that readable stream, it will call that listener with that chunk of data. You can read a lot more about readable streams in the node doc to understand better how they work.

  5. The listener for the end event tells you when the readable stream has finished giving you its data.

When did server add listener to request in node?

This happens each time there is a new incoming http request to the server. That's when the callback to the http.createServer() is called. And, for each new incoming request, a new http.IncomingMessage object is created for that callback.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download