Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Web Development with MongoDB and NodeJS Second edition

You're reading from   Web Development with MongoDB and NodeJS Second edition Build an interactive and full-featured web application from scratch using Node.js and MongoDB

Arrow left icon
Product type Paperback
Published in Oct 2015
Publisher
ISBN-13 9781785287527
Length 300 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (14) Chapters Close

Preface 1. Welcome to JavaScript in the Full Stack FREE CHAPTER 2. Getting Up and Running 3. Node and MongoDB Basics 4. Introducing Express 5. Templating with Handlebars 6. Controllers and View Models 7. Persisting Data with MongoDB 8. Creating a RESTful API 9. Testing Your Code 10. Deploying with Cloud-Based Services 11. Single-Page Applications with Popular Frontend Frameworks 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.

You have been reading a chapter from
Web Development with MongoDB and NodeJS Second edition - Second Edition
Published in: Oct 2015
Publisher:
ISBN-13: 9781785287527
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image