© Kanika Sud 2020
K. SudPractical hapihttps://doi.org/10.1007/978-1-4842-5805-7_2

2. Beginning Node.JS

Kanika Sud1 
(1)
Kanika, Chandigarh, India
 

We now have an understanding of what REST APIs are, and it’s time to understand Node.js in a larger context. This chapter covers what Node.js is. We take a brief look at Node.js and differentiate it from Node. The two are often confused or interchangeably used. We start by understanding the popularity of Node.js and how it became the go-to point for REST APIs. If you’re a solution architect trying to understand which tech stack to use, this could be the chapter you want to read, considering hot topics like which stack to use for mobile app backend development. We end by looking at the possible downside of using Node.js without a framework and a very brief description of Node.js modules.

Quick Popularity

In a very recent discussion forum on a technically aware community, we discussed why Node.js gained popularity in REST APIs. Before beginning to understand Node.js, we’d like to point out a few trends that modern web apps are following.

“Write Everything in One Language” Approach

Somewhere down the line, the dev community preferred to reduce everything to just one language while making a solution. This is in most of the cases. For instance, JPA for the Java community became very popular for the same reason. Any tech stack, written completely in JavaScript, was bound to be popular and especially attractive for smaller web apps, because you’re frequently expecting JavaScript expertise for the client-side logic.

“A Server and an App in One” Approach

Q: Now, a server being an application itself...as opposed to one server handling many applications. How do you think that differs or alters performance, and which would you prefer?

A: Historically, it would be one server hosting many apps. But not so anymore. Considering that (i) clustering servers is not the need of the hour, you can slot in more processing powers through more CPUs and (ii) lightweight servers like Tomcat, Jetty, and Node.

Consider Spring Boot . It’s like Node.js in that the app and server are one, but at the same time it’s different, because what you really have is still a separation between the web app and the web app server. It’s just not as visible because Spring Boot wraps both of them together. Node.js doesn’t separate the server code from the app code, so there’s an even greater potential for sharing resources between the two. Now if you’re designing a REST API, Node.js is just the choice.

The Titans vs. the Public

There was a time when technology meant only enterprise-level applications. The world belonged to large consultancies, who served financial institutions, healthcare, and the like, heavy risk, heavy data-driven apps over load balancers to enterprises where technology could make a difference of life and death, not only a million dollars. Welcome, small-scale world for the common public. When technology was introduced for everyday reasons, “lighter” tech was introduced too. When security isn’t a huge concern, Node.js easily wins the game because of the sleek way it fits into the MEAN stack. Assembling exactly what you need and plugging it into Read Write Serve is a straightforward task in the NPM ecosystem, thanks to the many packages you have. Borrowing from Object-Oriented Programming, the small-scale tech world carves its own niche, and JavaScript and Node.js lead because their libraries and modules are proven winners for quick solutions when your go-to market plan timelines are tighter. You’d only be glad to use JavaScript for an end-to-end client- and server-side stack in entirety.

The Big Reason: Asynchronous, Non-blocking Model

This is not a book on JavaScript, and hence we cannot dive deep into what JavaScript does and how it works. If you know very little about JavaScript and are still looking to migrate to Node.js and its frameworks from a non-JavaScript background, I’d recommend a basic understanding through reading and videos of
  • Call stack

  • Asynchronous

  • Callbacks

We’ll look at all these in Chapter 3 when we walk you through the essentials of JavaScript – just so that you know what’s happening when we’re working in hapi.js. Please note that nothing in JavaScript is asynchronous in itself. It’s to say that JavaScript allows for the asynchronous programming model. And Node.js runtime takes full advantage of it.

Here, we’re telling you how traditional models spawn a thread for each request. This system waits for a request to be handled and then processes the next. Even in a multi-threaded environment, handling threads through your application programming is a messy business. How about a nice little world, where the server itself is asynchronous and non-blocking and does not “wait” for a request to complete before the next one? How that happens internally – the event loop – most developers would not need to bother about in everyday REST APIs (don’t worry, we’ll make sure you know these concepts too). The short story is that asynchronous handling made Node.js very popular.

This chapter is a very short chapter on the popularity of Node.js, but before we end it, we want you to understand the internal working of something called the event loop . In this chapter, we take a sneak peek with a real-world analogy. In the next chapter, when we’re dealing with real JavaScript code, we revisit the concept for a better, more thorough understanding.

Imagine a simple scenario when you’re cooking at home. Now, when you’re on a single stove, you wait for the dish to get cooked. It’s awesome that you now have two stoves. But would that, rather, should it limit you to cooking two dishes at a time? And if you were to cook ten dishes for some reason, would you buy more stoves? No. Similarly, in Node.js you don’t spawn a new thread for every new request. A process (cooking) requires one thread (one stove). Multiple background processing can happen for I/O, but your app logic does not handle them. So much for the single-threaded environment. And what if you have someone helping in the kitchen who can check when the dishes are ready while you prepare your batter for a cake and similar stuff? What’s that called? Productivity. Remember the help is just checking what dishes are ready and where your attention is required. That’s your event loop.

Figure 2-1 provides a visual that could help understanding it.
../images/494274_1_En_2_Chapter/494274_1_En_2_Fig1_HTML.jpg
Figure 2-1

Node.js Event Loop

The V8 JavaScript Engine

First things first, all browsers have a JavaScript engine which they use to execute JavaScript at runtime. The DOM and the other Web Platform APIs are provided by the browser. V8 happens to be the engine that runs JavaScript in Chrome. However, it is not coupled with Chrome which enabled the rise of Node.js. V8 was chosen to be the engine that powered Node.js back in 2009, and it proved to be just the right choice, as its popularity exploded. JavaScript is internally compiled by V8 with just-in-time (JIT) compilation to speed up the execution. On the Web, there is a race for performance that’s been going on for years, and what this means for us is that every engine made for the browser can independently host a JavaScript runtime. It is exactly for these reasons that a V8-powered JavaScript runtime became powerful, while V8 was continuously improved for Chrome.

The Benefit in Microservice Architecture

Prior to the microservice architecture, there was the monolithic architecture, where the UI interacted with one single business logic layer, which interacted with the database layer (Figure 2-2). With a microservice architecture, developers are looking at modular approaches to manage their code across business-oriented modules, for better organization and maintainability. It also has deep effects in deploying and testing applications. The application starts faster, which makes developers more productive and speeds up deployments. I have personally seen this across an application which had to be distributed across seven microservices for it to make sense – and was otherwise a developer’s hell when introduced to it. We could isolate bugs better and make a longer commitment toward product maintenance than we would have otherwise.
../images/494274_1_En_2_Chapter/494274_1_En_2_Fig2_HTML.jpg
Figure 2-2

Monolithic vs. Microservice Architecture

Microservice and Node.js Go Hand in Hand

The three main reasons I’d recommend Node.js for a microservice architecture would be
  1. 1.

    Faster execution

     
  2. 2.

    Simplified, modular development

     
  3. 3.

    API support and easily available frameworks

     

It seems as if the aim behind the use and creation of both the architecture and the runtime is the same – and that is why, when coupled, they do fairly well.

Node.js Frameworks

Before understanding Node.js frameworks, let’s make sure we know ample about Node.js itself. Try out a few sample apps and small programs and do visit learning tracks like this:

https://nodejs.dev/

What we intend to do in this section is to introduce you very briefly to some frameworks of Node.js which are up on the market to catch up with. Why use a Node.js framework at all? Well, you get to work with a set of tools, guidelines, and recommended practices that help you save time. The core modules of Node.js including the file system module and the HTTP module can be used in many ways; and when you need to set standards of a product, you work over and above a set of utilities provided by a framework, not by the language itself.

Among hapi, Express, Meteor, Koa, Next, LoopBack, and many others, hapi does not receive many stars on Github, but it won’t fade away anytime soon, considering the backing it has (supported by Walmart Labs).

Here’s a list of Node.js frameworks online:

http://nodeframework.com/

When selecting a framework, do look for your own requirements fitting into the framework. For instance, for people looking for availability of caching, request handling, authentication, and input validation, they can rely on hapi because of its amazingly secure family of hapi plugins. For developers looking for minimalist solutions, Express might also be an option. If you’re the kind looking for a framework that enforces a folder structure, try LoopBack.

The reason why we choose to study hapi is because its MVC structure and in-depth control over core modules of Node.js enable the developer to migrate to any other framework easily, once a knack is established with it.

Summary

The main aim of this chapter was to give you a glimpse of why Node.js is very popular. While this covers practical aspects of hapi.js, we’d want you to have a good knowledge of why Node.js is very popular. This chapter was just a gist. We also learned a little about evolving trends in technology – the server and the app in one, one language for the whole solution, and how everyday technology requires quick-to-deploy solutions, rather than enterprise tech with a slower, tougher learning curve. And lastly, our key take-away should be the single-threaded asynchronous model, which doesn’t block any resources. I hope the analogy wasn’t rough. What matters is what you take from it. We’re going to dig deep into asynchronous programming and event loop in the next chapter, practically understanding essentials of JavaScript – and we’re excited!

Further Reading

A good summary for solution architects and for developers who get excited by newer technologies, not knowing where to use them! – www.toptal.com/nodejs/why-the-hell-would-i-use-node-js

A look into microservice architecture with Node.js – www.monterail.com/blog/nodejs-development-enterprises

A good article about microservices and Node.js – https://nodesource.com/blog/microservices-in-nodejs

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.72