In my last post we discussed how nodejs can be used to create a http server, but it had some practical problems associated with it. Our ready to deploy server can listen to incoming request on designated port, but it simply didn’t know what to do next ! We discussed the need of routing handlers. We also left the topic of  ” asynchronous programming” to be covered later.

My so far experience with nodejs tells me that “asynchronous programming” is the deal, it is what that differentiates node from everything else, so how do we explain that ?. Lets go back to elementary school. Sure we all do have had hands on programming languages like “BASIC” or event a little of batch programming on windows. A simple “Hello World” would in BASIC would be written like this

Poor BASIC everybody forgot you !, It was surely the coolest stuff when I was just a 5th grader. Of course this is stupidity now, you decide the flow of your program, and external influence doesn’t really influence the flow, things went on like this with many other programming languages and we heard a new concepts of modular programming and OOPS. Sure these are cool concepts but you’re still deciding the flow ! It’s just that external influence do influences your flow, but then lets say, you’ve heavy database driven application and somewhere in your code you’ve this snippet:

What if all these individual modules are independent of each other ? Database and File I/O are blocking process, that means doSomeAction() and doAnotherAction() will have to wait untill Database and File I/O perform and release the control ! This form of programming is called Synchronous Programming, on the other hand NodeJS adapts Asynchronous Programming methdology, which means every module ( technically its called an event, we’ll just call it a module for simplicity and analogy ) has this unique feature of “callback“, its says ” Okei guys I’m doing something, whenever I’ll be finish with my operation, I’ll do the callback, in the meanwhile you can continue your normal routine, I won’t block it”

How do we illustrate this ? lets go back to our Simple HTTP Server that we created

Here,  we actually wait for an incoming connection, and whenever we get a connect we simply make a callback to function(req,res) which renders content to our page.

About Events and listeners

The very reason that nodejs is faster is because it is based around events and asynchronous programming. Instead of initiating everything to process even 1% of your code ( like PHP ) it simply creates a server, initiates a few necessary things and wait ! It simply waits for an event to occur, there is a totally separate handle called “event-loop” to handle events listening and handling them. We write relevant event listeners for possible events that our program may receive. Our event-loop works independently, and whenever an event occurs it simply initiates the required listener, how stupendous that is  !

Nodejs comes with powerful library to deal with events, we can create our own events, listen to them and handle them. Lets just start by emitting an event, for this we require a core module “events” and the EventEmitter() method. Let’s start by emitting an event of knocking on the door.

var events = require('events');
var eventEmitter = new events.EventEmitter();
var knockDoor = function knockedMyDoor(){
console.log('Opening the Door');}
eventEmitter.on('knockMyDoor', knockDoor);
Wait ! stop reading the code in the given order! Lets do some autopsy of this code.
Line 1: We Imported the “event” module
Line 2: We created an instance of EventEmitter
Line 3-4:We created a simple function knockedMyDoor() that will open the door.
Line 4: We are “listening” to an event ‘knockMyDoor’, and associating it with a handle which will call function we created earlier.
Line 5: We emitted an event “knockMyDoor”

Whenever we’ll emit knockMyDoor, our event handler will call knockedMyDoor to open the door ! beside eventEmitter.on() there are few other methods which help us in listening to events.

We can create multiple handlers to a single event like

More APIs can be found at official docs here
One of the interesting API is once(), which is slightly different from on(), while on() will listen to the event every time it occurs and handle it, once() will only listen to it for 1 time and will ignore it further. How useful is that ? even I was struck at this point until yesterday, then I acknowledged how good this is, I had a database operation which was initiated whenever the database connection was “open” ( an event) I started with on() method and since the connection was “open” for a long time, my event listener used to perform redundant actions, to stop this, I had to move to once() and it was pretty simple then.
By the end of this part we have covered most concepts and theories related to nodejs, and now we’ll try and focus more on the code part from the next part.