Getting Started With Node.JS

at in articles

Summary

  1. What Is Node
  2. Main Characteristics
  3. How To Install Node
  4. Running Node
  5. Package Managers
  6. Tools And Frameworks
  7. Case Studies
  8. References
  9. Conclusion

What Is Node

Node is a Javascript runtime originally built on V8 JavaScript engine, which is a high-performance engine for Webassembly and ECMAScript written in C++ initially created for Chrome browser.

It is one of the most used technologies for web development at the moment, according to the 2018 StackOverflow survey more than 49% of the participants of the survey use Node, and more than 69% use Javascript as their primary language.

These numbers are impressive and they don’t appear to be going down anytime soon. Due to its flexibility and performance Node can be a very good choice for high concurrence/high load systems.


Main Characteristics

Ok, these numbers are indeed remarkable, and maybe you’ve already heard about how fast Node can be, but what exactly makes it special, or any different?

Let’s break down the main characteristics:

  • Event-driven/Asynchronous/Non-blocking: The famous event loop allows Node to perform asynchronous non-blocking calls, which is one of the key factors for its performance.

  • Single Threaded: Yes, true, Node event loop is single threaded but there is a catch, it has background workers for blocking I/O operations, this way can be very resource-economic while being able to handle a great number of requests. And it is relatively easy to tune node to take full advantage of a multi-core server.

  • It’s Javascript: This is really significant, developers were allowed to leverage their existing Javascript expertise to take advantage of a performant server-side technology, definitely, this was critical for its popularity.

P.S: If it is still unclear to you how exactly the event loop works, stop, take a few minutes to watch this video, this guys named Phillip Roberts nails it.

It is the best explanation on the topic that I’ve seen so far.


How To Install Node

Here we will cover only Ubuntu 18.04 and MacOS Mojave 10.14.2 installations because these are the systems that I use.

If you use Windows here is a detailed installation post.

Both installations also install NPM and Yarn package managers, we will talk a bit about them later.

On Ubuntu using APT

APT or Advanced Packaging Tool is the default package manager for Ubuntu.

# update the index of packages 
sudo apt update
# install the available Node version, in my case was v8.10.0 
sudo apt install node -y

On Mac OS using Brew

Installing Node is a very straightforward process with Brew, which is a very handy package manager for MacOS.

Here is how to install Brew:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then, proceed to the Node’s installation:

brew install node

Check installation

To verify if everything went well, check for the version of the installed package.

# Should return the installed version of Node, ex: 11.11.0
node -v


Running Node

Now that we have it installed, is time to run our first scripts. We will go through two examples, one simple Hello World from the command line and a Hello World from a web server.

Hello World - Command line

Let’s start by a very simple Hello World from the command line, create a hello-word.js with:

console.log('Hello World');

Yep, that’s right, exactly how you to debug stuff in the browser. Now you run it from the command line:

node hello-world.js

You should see your first node script result with the well known “Hello World”.

Hello World - Web server

Now let’s do something a bit more complex, a web server. Different from other languages, Node has a web server readily available via its HTTP module.

In this example, we will instantiate a new web server that will listen to the port 3000 and when requested will print “Hello World”.

Create a file called web-server-hello-world.js with the following content:

//requiring http module responsible for handling the requests
const http = require('http');
//the port the server will be listening to
const port = 3000;

//the function responsible for handling the incoming requests,
//it receives request and response objects as parameters
const requestHandler = (request, response) => {
      //let's log all the incoming requests
    console.log(request.url)
    console.log(request.headers);
    console.log('----------------');
    //and respond with a Hellow World
      response.end('Hello World');
}

//we instantiate the server passing the handler  function to 
const webServer = http.createServer(requestHandler);
//make the server listen to the port 3000
webServer.listen(port, (err) => {
//if something goes  wrong during execution we will receive an err
  console.log('Web server running, listening to port 3000');
  if (err) {
    //...and finish the execution writing the reason in the log output
      return console.error('An error occurred', err);
  }
});

Run it from your terminal with:

node web-server-hello-word.js

You should see a message this message on your terminal:

Web server running, listening to port 3000

It means that the server is running waiting for incoming requests, test it out, go to localhost:3000.

You will have our beloved “Hello world” printed in your browser.

Now go back to the terminal, you should see something like this:

/
{ host: 'localhost:3000',
	connection: 'keep-alive',
	'upgrade-insecure-requests': '1',
	'user-agent':
		'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
	accept:
		'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
	'accept-encoding': 'gzip, deflate, br',
	'accept-language': 'en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7,fr;q=0.6,it;q=0.5',
	cookie:
		'_ga=GA1.1.164623524.1552111574; _gid=GA1.1.1845491156.1552111574' }
----------------

/favicon.ico
{ host: 'localhost:3000',
	connection: 'keep-alive',
	'user-agent':
		'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
	accept: 'image/webp,image/apng,image/*,*/*;q=0.8',
	referer: 'http://localhost:3000/',
	'accept-encoding': 'gzip, deflate, br',
	'accept-language': 'en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7,fr;q=0.6,it;q=0.5',
	cookie:
		'_ga=GA1.1.164623524.1552111574; _gid=GA1.1.1845491156.1552111574' }
----------------

Which are the logs we added through out the code.

There you have it, a web server running in just a few lines.


Package Managers: NPM and Yarn

Package managers automate installing, upgrading, configuring, and managing dependencies of your software consistently.

Node ships with two options to manage your packages, NPM and Yarn, both of them access NPMs pool of packages but operate differently.

  • NPM: is the most famous package manager for Javascript, and it is the biggest registry for free and reusable software in the world.

  • Yarn: different from NPM, Yarn is just a cli tool that manages NPM packages, it was developed by Facebook to offer a faster, more secure, and uniform experience.

There is an intense debate to decide which one is best or in which scenario you should use what, some interesting arguments are laid here, here, and here if you want to know more.


Tools and Frameworks

The set of tools at our disposal is in part what makes a language or environment useful and in this area, Node shines, the range of tools available is amazing, and it is expanding.

Below is a list of some of my personal highlights:

  • Express: Let’s start with no other than the most famous Node framework of all, it is a minimalist and unopinionated web framework perfect for microservices and API’s. Easy to get up and running and extremely versatile this should be your first stop if you are starting out.

  • AllCountJs: AllcountJS is a full stack framework, offering all the tools needed to get a CRUD up and running fast.

  • Nodal Nodal is a framework focused on facilitating API creation process, offers a lot of solutions out of the box ranging from database migration system to controllers with standardized response views.

  • Connect Connect is an extensible HTTP middleware based framework from Sencha Labs.

  • Nasa’s OpenMCT Data visualization framework for the web, mobile, and desktop, it is gorgeous.

If you want to dig deeper and study more options for your projects I suggest this site, it is a curated list of Node frameworks organized by type, very useful.


Case Studies

The technology is widespread across the industry. You can find companies from basically any sector that has Node among their tools of choice.

Here is listed a handful of examples, with links to the full content, that in my opinion are relevant to showcase the possibilities.

  • Uber: node was one of the two main languages at Uber at the beginning alongside with Python. It is still used today on top of many different technologies.

  • Nasa: In this presentation from 2015, you will see how Node was a significant part of a great change at Nasa, help to integrate and visualize data driving the development of spacesuits.

  • Linkedin: The company was an early adopter of Node, the business-focused social network back in 2011 moved from Ruby On Rails to Node for the mobile backend and saw an amazing performance, up to 20x faster than the previous version.

  • Netflix: The streaming giant makes heavy use of Node in several points of their systems, from front-end to their A/B testing.

  • Walmart: At Walmart, most of their e-commerce website now is being powered by Node, in this article Joel Chen goes into the details of what actually takes to make such migration, it dives into much more than pure technical question it is very insightful.


References

There are a lot of other amazing publications but I’ve chosen the ones I’ve read and helped me the most.

Beginning Node.Js

This is a great first book, covers all the basics and offers good tools that will help to push your skills further.

Node.Js Design Patterns

Step up your Node game and dive into design patterns, good practices, and more advanced topics. I would suggest this one to the more seasoned developer, get a grasp before and build a solid foundation on the basics to extract the maximum from this book.

RESTful Web API Design with Node.js

If RESTful API is what you want to do with Node this is a must-have, quick refresh your memory on REST topics, covers code structure, good practices, databases and everything in between.


Conclusion

Node is able to perform practically anything that any other server-side language can, but in certain areas it has advantages, we already mentioned above the nonblocking nature of Node and when paired with WebSockets then the real disparity starts to show.

This combination allows a lot of interesting new options to real-time applications which is something you can somewhat achieve with other popular languages but at a certain cost and with much more complex strategies. So areas like the stock market, instant communication, gaming, etc, are an specially good fit for Node.

Node also performs exceptionally well with a more traditional stateless scenario that we are used to, microservices, APIs, single page applications. All that is perfect for Node.

Not to mention Serverless (If you need a refresh about serverless, check this out), here Node has a very special place, being practically the only constant among the serverless providers.

It is clear that all this rave about it has a very solid foundation, and now Node represents one of the go-to languages when we think about web applications. It resisted the trial by fire from many of the tech giants and proved to be a reliable and strong ally when it comes to building scalable and resilient applications.



See Also