Sunday, 18 August 2013

Node JS, createServer, and the Event Loop

Node JS, createServer, and the Event Loop

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
Event loop ticks
Node looks for any callbacks to run
Node runs those callbacks
Event loops ticks again, process repeats ad-infinitum
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)

No comments:

Post a Comment