NodeJS newbie – Basics

NodeJS newbie – Basics

NODE JS…a very popular buzzword in the developer world since 2009, yet there are very few good tutorials out there for it. This is where I feel I can pitch in, to formulate a single document to which newbies to NodeJS can refer to and get things kicking while getting a good understanding of the same.

Birth

Node.js was invented by Ryan Dahl (according to few quora reviews a very enigmatically modest, stealth programmer) in 2009 along with few other Joyent developers.

According to one of the stories he shared, It was all sparked by a demo which he viewed over Flickr.

You can read more about the article or watch this video where Ryan Dahl himself shared his history.

This document concentrates more on the beginners guide to get node.js started so lets do that without any more delay.

Introduction

First thing anyone would naturally do is visit the official website trying to figure out what it is, you would see this as the definition:

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Doesn't make much sense to a newbie right! Now you would drill down to the other pages and find few example codes, Ohhhh wow !! now everything makes sense to me(ya right!!). Basically they don't do a great job explaining to a complete beginner. Well let me try explaining. Put in simple words:

Node.js is a tool in which one can make really cool server side applications ie. if one is talking about a chat service, websites, social network site or even a game, this would definitely be a great choice. Another best part about node.js over say PHP is that, node.js is awesome for live real time updation stuff and also uses less memory comparitively.

For now just click the Download button and install the platform depending on your installer from here. Rest of the installation process is pretty self explainatory. If you face any problems check this page out.

Once you are done with the installation, you can verify by checking the node version installed from your terminal/command prompt via this command:

    node --version

Editor

This is ofcourse subjective, but the reason im mentioning it here is because i have come across few coders facing some minor problems pertaining NodeJS plugins and stuff.

Regarding an editor, WebStorm by JetBrains according to me is one of the best for building node applications.

The reason for this is that its preemptively setup for node development unlike other editors like Sublime, IntelliJ etc.

If your working on other editors say IntelliJ, we need to first install the plugin necessary to run node code without any warnings. To do this we need to go to:

File > Settings > Plugin (type NodeJS in the search bar) > Install plugin

once this is done, we now need to enable few libraries like so,

File > Settings > Languages & Frameworks > JavaScript > Libraries (Enable all node js related libraries)

Setup

Once the initial setup is complete, it is time we start writing some piece of node code.

  • First let us start by creating an empty directory.
  • Then create a file app.js inside it.

Directory Structure

For starters let us meddle only with this single app.js file to get a better understanding. In further chapters we will start working with multiple files.

Either ways in node app.js is usually the brain of the application. Our program is going to first look to app.js file and run the inhabiting code.

Few things to keep in mind

These are few points which could be obvious and basic but are also important to refresh since it becomes easier to understand and relate node. Also please note that these points need not be specific to node.

  1. In node, whenever we create objects they behave the exact same as in JavaScript.

  2. But very important thing to point out here is that unlike JavaScript, the node code will be running on your server(running continuously elsewhere on a server machine). For simplicity just imagine two different machines, one in which node server runs and a different client machine from which user requests are generated. All we need to know for now is that the code on the server machine will be continuously running to take requests. Again this not specific to node as these days almost all server side frameworks work continuously to handle requests. More on how Node handles multiple requests will be explained later in this document.

  3. In NodeJs like in JavaScript, we can assign an anonymous function to a variable.

  4. In Node everything is a reference. eg:

var Ferrari = {
    wheels: "four",
    color: "red"
};

var Car = Ferrari;
Car.color = "black";

console.log(Ferrari.color); //Result: black (we are not creating a copy but just getting a reference)

Also for beginners one of the really good to know thing is that whenever we have a function stored in a variable, we can easily pass them to another functions. One simple example of this is shown below.

var myName = function() {
    console.log("My Name is Slim Shady");
};
myName(); //Result => My Name is Slim Shady

setTimeout(myName, 4000); //Calls myName() again in 4 secs

Handling Multiple Requests in NodeJS

This is an important concept in NodeJS and hence to understand this better let's consider a real world example.


Say I own a CoffeeShop, I have a coffeeMaker who can make multiples coffees simultaneously but takes 3 minutes to prepare each. I have a waiter(server to take my requests). Let's assume I have 5 customers.

Considering the above(great) example, This is how my current system would work:

  1. Customer 1 asks for a coffee.
  2. Waiter takes the first request.
  3. Waiter gives the request to the coffeeMaker.
  4. CoffeeMaker takes 3 mins for the coffee to prepare.
  5. Waiter waits till the coffee is ready.
  6. Once done waiter takes the coffee to Customer 1.
  7. Now Waiter takes the request of Customer 2 and so on…

Now as we notice, this process takes 3 minutes for each order to be processed by a single server(the waiter). Which means if I have 5 customers the total time taken to serve all the coffee requests will be 15 long minutes. So if there were say 100 customers, I definitely wouldn't want to go to that CoffeeShop! Now how can I possibly improve the efficiency of my CoffeeShop. One way would be to simply hire more waiters to take multiple requests, well i'm trying to run a CoffeeShop afterall which means i cant afford a waiter every now and then.

Hmmm so let's think … Well another smart way to deal with this is by tweaking the way in which my entire system processes requests. Now let's consider this is how my new system would work:

  1. Customer 1 asks for a coffee.
  2. Waiter takes the first request.
  3. Waiter gives the request to the coffeeMaker.
  4. CoffeeMaker takes 3 mins for the coffee to prepare.

Now here, instead of the Waiter waiting for the coffee to be prepared, he uses this time to take the next coffee request.

  1. Takes coffee request from Customer 2.
  2. Waiter gives the request to the coffeeMaker.
  3. Takes coffee request from Customer 3 and so on.

Once all the requests are given to the coffeeMaker, he then tells the coffeeMaker to call the waiter back once all the requests are ready(this is called callback). So finally after 3 mins we see that all the coffee requests are prepared and the waiter then takes all the 5 coffees to the respective customers. Basically from 15 long minutes we reduced the time taken to 3 mins. Now isn't that freaking amazing!?

Now this is exactly how NodeJS works, making it much faster catering to thousands of requests in just few milliseconds.

Let's demonstrate the same via code.

function getMyCoffee(customerNumber) {
    console.log("Order from customer number: " + customerNumber);

    prepareCoffee( function() {
        console.log("Prepared Coffee for Customer: " + customerNumber);
    });
}

// Lets consider this takes 3 seconds
function prepareCoffee(callback) {
    setTimeout(callback, 3000);
}

// Take Customer Requests
getMyCoffee(1);
getMyCoffee(2);
getMyCoffee(3);
getMyCoffee(4);
getMyCoffee(5);

When we run the above code in our app.js we will see the following results:

Order from customer number: 1
Order from customer number: 2
Order from customer number: 3
Order from customer number: 4
Order from customer number: 5

// After 3 seconds //

Prepared Coffee for Customer: 1
Prepared Coffee for Customer: 2
Prepared Coffee for Customer: 3
Prepared Coffee for Customer: 4
Prepared Coffee for Customer: 5

// All the 5 coffees are ready at once //

I can sense a lot of people getting confused at this point asking, we set the setTimeout(callback, 3000) to 3 seconds. So how is it that we are able to hop on to the next request before 3 seconds(aren't we waiting for 3 seconds).

To clear this confusion, we got to keep in mind that, what we are trying to tell the program by this line of code is – setTimeout(callback, 3000) :

"Schedule the callback to fire that particular piece of code when you are done, in this case -> console.log("Prepared Coffee for Customer: " + customerNumber); in 3 seconds. Meanwhile I will continue with the rest of the program"

and NOT "Wait 3 seconds, pause the program for 3 seconds and then fire the callback function" – NOPE!

This is exactly what node does not do, hence one of the reasons why node is much more performant and preferred.
Whats makes Node different is that it has only One thread handling all the requests(which in our example was that One waiter).


I think this is good enough information to cover the basics. Look out for my next blogs where I will be talking about Prototype, Creating a server, Modules … in NodeJS.

Regarding the maintenance of NodeJS, as the image shows below it is very much active and is contributed constantly by 700+ contributors.

NodeJS Github

So if NodeJS really interested you, keep yourself updated by following it on…

NodeJS Community – Facebook

NodeJS Community – Twitter

Leave a Reply

Your email address will not be published. Required fields are marked *