Behind the scenes in node, how does the http module's createServer method (and its callback) interact with the event loop? Is it possible to build functionality similar to createServer on my own in userland, or would this require a change to node's underlying system code?
That is, my general understanding of node's event loop is
What I'm still a little fuzzy on is how createServer fits into the event loop. If I do something like this
var http = require('http');
// create an http server and handle with a simple hello world message
var server = http.createServer(function (request, response) {
//...
});
I'm telling node to run my callback whenever an HTTP request comes in. That doesn't seem compatible with the event loop model I understand. It seems like there's some non-userland and non-event loop that's listening for HTTP requests, and then running my callback if one comes in.
Put another way — if I think about implementing my own version version of createServer, I can't think of a way to do it since any callback I schedule will run once. Does createServer just use setTimeout or setInterval to constantly recheck for an incoming HTTP request? Or is there something lower level, more efficient going on. I understand I don't need to fully understand this to write efficient node code, but I'm curious how the underlying system was implemented.
(I tried following along in the node source, but the going is slow since I'm not familiar with the node module system, or the legacy assumptions w/r/t to coding patterns deep in the system code)
http.createServer is a convenience method for creating a new http.Server() and attaching the callback as an event listener to the request event. Of course the node http library implements the protocol parsing, as well.
There is no constant polling of the event loop, node is waiting for the C++ tcp bindings to receive data on the socket, which then marshall that data as a buffer to your callback.
If you were to implement your own http parser, you would start with a net.Server object as your base. See node's implementation here: https://github.com/joyent/node/blob/master/lib/_http_server.js#L253
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With