Book Image

Web Development with MongoDB and NodeJS Second edition

Book Image

Web Development with MongoDB and NodeJS Second edition

Overview of this book

Table of Contents (19 chapters)
Web Development with MongoDB and NodeJS Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
12
Popular Node.js Web Frameworks
Index

A short introduction to Node.js


One of the most important things that people get confused about while getting introduced to Node.js is to understand what exactly it is. Is it a different language altogether, is it just a framework on top of it, or is it something else? Node.js is definitely not a new language, and it is not just a framework on JavaScript. It can be considered as a runtime environment for JavaScript built on top of Google's V8 engine. So, it provides us with a context where we can write JavaScript code on any platform where Node.js can be installed. Anywhere!

Now a bit about its history! Back in 2009, Ryan Dahl gave a presentation at JSConf that changed JavaScript forever. During his presentation, he introduced Node.js to the JavaScript community. After a roughly 45-minute talk, he concluded it, receiving a standing ovation from the audience in the process. He was inspired to write Node.js after he saw a simple file upload progress bar on Flickr, the image-sharing site. Realizing that the site was going about the whole process the wrong way, he decided that there had to be a better solution.

Now let's go through the features of Node.js, which makes it unique from other server-side programming languages.

The advantage that the V8 engine brings in

The V8 engine was developed by Google and was open sourced in 2008. As we all know, JavaScript is an interpreted language and it will not be as efficient as a compiled language, as each line of code gets interpreted one by one while the code gets executed. The V8 engine brings in an efficient model here, where the JavaScript code will be compiled into machine-level code and the executions will happen on the compiled code instead of interpreting the JavaScript. But even though Node.js is using the V8 engine, Joyent, which is the company that is maintaining Node.js development, it does not always update the V8 engine to the latest versions that Google actively releases. This has led to the new branch named io.js, which we will discuss later in this chapter.

Node.js is single threaded!

You might be asking, how does a single threaded model help? Typical PHP, ASP.NET, Ruby, or Java-based servers follow a model where each client request results in the instantiation of a new thread or even a process. When it comes to Node.js, requests are run on the same thread with even shared resources. A common question that is often asked is what will be the advantage of using such a model? To understand this, we should understand the problem that Node.js tries to resolve. It tries to do asynchronous processing on a single thread to provide more performance and scalability for applications that are supposed to handle too much web traffic. Imagine web applications that handle millions of concurrent requests; if the server makes a new thread for handling each request that comes in, it will consume a lot of resources and we would end up trying to add more and more servers to increase the scalability of the application. The single threaded asynchronous processing model has its advantage in the previous context, and you can process much more concurrent requests with less number of server-side resources. However, there is a downside to this approach; Node (by default) will not utilize the number of CPU cores available on the server it is running on without using extra modules like pm2.

Note

The point that Node.js is single threaded doesn't mean that it doesn't use threads internally. It is just that the developer and the execution context that the code has exposure to have no control over the threading model internally used by Node.js.

If you are new to the concept of threads and process, we would suggest you to go through some preliminary articles about these topics. There are plenty of YouTube videos as well on the same topic. The following reference could be used as a starting point:

http://www.cs.ucsb.edu/~rich/class/cs170/notes/IntroThreads/

Non-blocking asynchronous execution

One of the most powerful features of Node is that it is event-driven and asynchronous. So how does an asynchronous model work? Imagine you have a block of code and at some nth line you have an operation that is time consuming. So what happens to the lines that follow the nth line while this code gets executed? In normal synchronous programming models, the lines that follow the nth line will have to wait till the operation at that line completes. An asynchronous model handles this case differently. To handle this scenario in an asynchronous approach, we need to segment the code that follows the nth line into two sections. The first section is dependent on the result of the operation at the nth line and the second section is independent of the result.

We wrap the dependent code in a function with the result of the operation as its parameter, and register it as a callback to the operation on its success. Once the operation completes, the callback function will be triggered with its result. Meanwhile, we can continue executing the result-independent lines without waiting for the result. In this scenario, the execution is never blocked for a process to complete. It just goes on with callback functions registered on each ones completion. Simply put, you assign a callback function to an operation, and when Node determines that the completion event has been fired, it will execute your callback function at that moment.

We can look at an example to understand the asynchronous nature in detail:

console.log('One');
console.log('Two');
setTimeout(function() {
   console.log('Three');
}, 2000);
console.log('Four');
console.log('Five');

In a typical synchronous programming language, executing the preceding code will yield the following output:

One
Two
... (2 second delay) ...
Three
Four
Five

However, in an asynchronous approach, the following output is seen:

One
Two
Four
Five
... (approx. 2 second delay) ...
Three

The function that actually logs Three is known as a callback to the setTimeout function.

Note

If you are still interested in learning more about asynchronous models and the callback concept in JavaScript, Mozilla Developer Network (MDN) has many articles that explain these concepts in detail.