Node.JS Explained Raw…

Harsh Kashyap
8 min readAug 26, 2018

--

What the fu*#k is this Node.JS ?? Is it a framework, a library , or a new programming language?? Since its first release in 2009, Node.JS has become a buzzword for the techno-junkies in the WEB world (even the non-tech ones), and the Node.JS bandwagon has not stopped since then… But sadly, there is that thick air of uncertainty, or confusion regarding Node.JS as a technology, which is simply attributed to the fact that it is new, something which has been never been made before… Unlike PHP, Python, Ruby, the traditional , popular backend -languages, Node.JS has much much more to offer and we can only leverage its power , if we come out of our shells and dive deep into the system and appreciate the beauty Node.JS is… As is rightly said by Ryan Dahl, the man behind Node.JS…

“ You can never understand everything. But, you should push yourself to understand the system.”

Keeping this in mind, I will try my best to help you understand Node.JS in simpler terms , breaking it into small fragments, and in the process, helping you unveil the beast Node.JS is…

We’ll start off with the historical background of Node.JS…

HISTORY

In March 2011, a video (shown below) began circulating on youtube among developers, where a 20 -something old guy named Ryan Dahl was giving lecture to a small group at San Francisco meetup , where he was talking about a new way to write javascript on server. He said that , he had packaged up Chrome’s V8 runtime so that it can interpret javascript server -side on any UNIX like machine, and he had also added some useful APIs under the hood, and he was calling his creation Node.JS. Everyone seemed to be confused, running a browser-oriented language on server- side was something hard to digest for the community , but then it’s a norm for every revolutionary idea, Isn’t it ?

In order to define Node.JS, we’ll first have to first understand what V8 is, how it works and what are Javascript engines in general ?

What is V8, exactly?

To have a complete hold on V8, we’ll have to take a step back and revise some of the key points leading to the concept of Javascript Engines (V8), let’s start:

  • Machine Code => Modern computers only understand machine code, which are nothing but strings of 1s and 0s.
  • Programming Languages => Now, it’s understood that writing machine code is practically impossible, that’s why programmers use programming languages like C++, Javascript, Java, Python etc. also known as “high-level” code. It hides away the CPU- level operations like loading the disc, storing , writing data to RAM etc. , and let the programmers create their variables and perform calculations, execute functions and much more. This method of implementing programs without going into operational-details is also known as Abstraction.

In order to execute high-level code, computer mostly uses:

  • Compilers => Takes the source code and turns it into an executable file (a file full of code that computer can execute)
  • Interpreters => Takes source code and execute it directly in realtime intermediatary steps, leaving nothing behind for computer to execute. In nutshell, Working of Interpreters = Compiling + Executing (in real-time).

Now, V8 is a Javascript Engine (embedded in chrome) which in turn is an interpreter for Javascript. It takes your javascript code and compiles it into the machine code and executes it. It also optimises the code during runtime to make it more fast and efficient.

Javascipt-engines are also known as “Javascript virtual machines”, embedded in the browsers with different “codenames”, for example:

Now, Coming to Node.JS, It is an application written in C++ which embeds V8 in order to execute JS much like how browser does . It looks for javascript files and then send those files to its embedded javascript engine(V8) for code execution.

Now, we are well versed and equipped to define Node.JS.

What is Node.JS ?

Node.JS is a server-side javascript-runtime built on Chrome’s V8 Javascript engine.

Let’s elaborate the above definition:

Node.JS is an application, a platform, or a javascript-runtime which is built on top of Chrome’s V8 Javascript-Engine that looks for javascript files and executes it on the computer.

Over the time, working on Node.JS, Ryan Dahl and other contributors have made two primary programs or environments on node.js , both of which can be run directly from your command line.

  • A Script Processor
  • A REPL (Read Eval Print Loop)

Script Processor

Script Processor can be invoked simply by using:

node {script name} // Eg -> node index.js

In this scenario, we are passing the script name (index.js) to node.js , so that node can open the file and process the javascript code inside it.

But, it’s a bit more complicated than it seems:

When we invoke the node in this manner, it’s not going to send the javascript files directly to the V8 for its execution, rather it initialises the process called Event Loop first, and then it’s going to process initial parts of your javascript file , after which it will start processing the event loop initialised earlier.

Now, what the heck is Event Loop?? Let’s find out…

Event Loop

Event loop is an infinitely running task that starts over as soon as it completes. The “event loop” is continually checking if there’s anything for node.js to do.

Wait wait wait…You might be wondering that didn’t node.js process the file at the beginning before it started the event loop…

Well, Both YES and NO.

Here comes the beauty or rather weirdness of Javascript language. It (javascript file) includes both synchronous and asynchronous behaviours.

Synchronous behaviours are executed by node as soon as it is encountered. For eg-

console.log("hi");console.log("harsh");console.log("there");// The output of the above code will behi
harsh
there

While, Asynchronous behaviours are simply invoked and not executed instantly. Instead, these are added to the task queue, which lists every asynchronous tasks . The event loop is node’s way of processing the task queue. With each tick of the loop , it completes an item or several items in the queue which might create more asynchronous operations and the application will keep on running until there’s some work present in the task queue.

Once, all the asynchronous tasks have been processed by event loop and the task queue is empty , the application exists.

console.log("hi");setTimeout(function(){
console.log("harsh")},1000);
console.log("there");// The output of the above code will behi
there
harsh

Here, in the above example setTimeout is called asynchronously and thus it will be added to task queue for its further processing. Hence it will be processed after all the synchronous commands have been executed.

The concept of Event Loop might get little trickier, and it’s bit hard to digest it at first. Below is one of the best video which will clear all your doubts surrounding Event Loop. Do check this out.

Items that can be added to the Queue can be any task which should not be executed synchronously such as those including callbacks or those whose execution is scheduled for the later time (such as time-outs, time-intervals). Such umbrella of tasks are also known as Non-Blocking.

Advantages of Non-Blocking I/O

In many programming languages, everything we do is Blocking, i.e if we have a sequence of tasks that needs to be performed, the our single threaded app will execute each task in order and while doing so, it is incapable of doing anything else.

Blocking tasks or the runtime with Blocking I/O have their place if you need to perform your tasks in exact same order and there is nothing else your thread rather be doing in that time, then there’s virtually no drawback to Blocking I/O but that’s not the case always.

Modern web apps need to handle and process multiple things at a single time, they might be fetching data of one user from the database, logging in the other user, processing the credit card of yet another another, or sending the mail to the other all at same time. So, how does a Non-Blocking I/O helps node do multiple things at same time. Well, it doesn’t.

As we know, Node.JS is single threaded, it can only do one thing at a time. The Non-Blocking I/O doesn’t allow Node to do multiple things at a same time, it just allows Node to schedule things later. This may sound trivial but it’s one awesome thing happening in back-end. Let’s see with an example:

Let suppose, You have a single threaded Blocking programming language.Your API got a POST request for the creation of new user, you will collect the users’ data , parse it and then send the data to the database, will wait for the database to process the data and finally respond you back. Well, while your code is waiting for database to respond, it’s blocked. It might want to perform other tasks at that time such as routing requests of different users, performing background tasks etc. but it just can’t due to the blocking behaviour of your API. It can’t respond to third party APIs, can’t get information from database, can’t perform reads and writes on the disk. It is just blocked from doing anything else and is stuck in the state of idleness.

Non-Blocking I/Os and Event Loop are the answers to this problem, when the node is faced with the same API request, it will take the user’s data, parse it synchronously just like any other API, but when it has to send the information to DB, it will just send off the data and will add an item to the Todo list (Task Queue) saying whenever the database responds, process the response.So now, while the database is processing the data, Node.js thread will move onto other tasks like processing requests of other users etc. This way, Node is never in the state of idleness and it keeps reprioritizing it’s tasks until it completes.

And, This is how Node processes JS.

REPL (READ EVAL PRINT LOOP)

REPL is an interactive JS runtime . It works much like the console within web browser. It is a way to define and execute javascript code against V8 javascript engine in real time.

REPL can be invoked by just entering:

node // it will start REPL

Node will start the REPL and you will see a cursor marker appear in the terminal which tells you that REPL has started R phase of its process, i.e. reading input from you.

Node will start the event loop and will wait for you to write your javascript code and the process will be same as described in SCRIPT PROCESSOR.

Thank You

I hope this introduction helped you get a better understanding of Node.JS.

This is my first POST on medium, and if you feel like I have done some good work and added value to your understanding of Node.js, please give a clap to this article so that to spread this (post) among wider audience and help them understand Node.js. better.

--

--