Soni Pandey
2 min readApr 25, 2016

How function passing makes our HTTP server work

In the last article, we have setup our http server in node.js. There, we didn’t discuss, how createServer function passing makes our HTTP server work. Let’s have a look to server function:

By now it should be clear what we are actually doing here: we pass the createServer function an anonymous function (onRequest). We could achieve the same by refactoring our code to:

Maybe now is a good moment to ask: Why are we doing it that way?

if Node.js would start the server and then just pause, waiting for the next request, continuing only when it arrives, that would be highly inefficent. If a second user requests the server while it is still serving the first request, that
second request could only be answered after the first one is done - as soon as you have more than a handful of HTTP requests per second, this wouldn’t work at all.

Node.js is just one single process, and it can run on only one single CPU core. Can we prove that our code continues after creating the server, even if no HTTP request happened and the callback function we passed isn’t called? Let’s try it:

When we start this (node server.js, as always), it will immediately output ”Server has started.” on the command line. Whenever we request our server (by opening http://localhost:9999 in our browser), the message ”Request received.” is printed on the command line.
Event-driven asynchronous server-side JavaScript with callbacks
in action :-)

Ok, let’s quickly analyze the rest of our server code, that is, the body of our callback function onRequest(). When the callback fires and our onRequest() function gets triggered, two parameters are passed into it: request and response. Those are objects, and you can use their methods to handle the
details of the HTTP request that occured and to respond to the request (i.e., to actually send something over the wire back to the browser that requested your server). And our code does just that: Whenever a request is received, it
uses the response.writeHead() function to send an HTTP status 200 and content-type in the HTTP response header, and the response.write() function to send the text ”Hello World” in the HTTP response body. At last, we call response.end() to actually finish our response. At this point, we don’t care for the details of the request, which is why we don’t use the request object at all. Soon, will come back with new article.

You can reach out to me for any doubt and suggestions. Please share this with others as well.

Oh, and if you like this, click the 💚 below. Keep watching this space and follow me for more articles on technology.

Thanks!
Happy Coding!!

Soni Pandey
Soni Pandey

Written by Soni Pandey

I am a Node.js Developer and eager to learn new technology. I blog, tweet & read whenever I can.

Responses (1)