What you need to know about Node.js? Short technology guide

At first, I need to explain some basics. Node.js is cross-platform, open-source Javascript runtime that works on so-called server-side. That means you can execute Javascript code on your computer using that runtime rather than running it in the browser.

I have to also point out that Node.js is not a webserver. It provides a way to write your own HTTP server or any other network services. Node.js also gives you access to filesystem and methods of operating with files and any other things that provide you the way to perform operations on your system.

Main features

  • Asynchronous and Event Driven – it means that API call doesn't wait for results and doesn't block other calls. After it finish executing it will run an callback or notify about certain execution parts using events. Even though Node.js is running on single thread with event looping, it can handle more requests than, for example Apache HTTP server, because of using asynchronous non-blocking way of handling code execution.
  • It's (very) fast – it's based on Google Chrome's V8 JavaScript Engine, which is very fast in executing JavaScript code..
  • High scalability - Thanks to the event mechanism Node.js can be easily scalable.
  • NPM (The Node Package Manager) - it's a tool that handles installing and updating of reusable modules from online collection. It also takes care of version and dependency management of reusable modules from online collection. NPM can be compared to Ruby Gems.
  • Community - there are a lots of community tutorials, resources or shared code. Node,js is very popular now and it became one of most of used technolgies used nowadays.

How Node.js works?

There are 3 main features that are standing behind Node.js architecture:

  1. Single threaded
  2. Main idea is that Node.js works on single thread. It might sound like a little bit like bottleneck, but in fact that approach is worth considering - for example it avoids context switching;
  3. Event Loop
  4. Event Loop is build on top of `libuv` which handles queueing and processing of asynchronous events. Event loop handles events queue which contains events with their callbacks. For example, when client send request to the Node.js server, the request handling function is placed into event queue and handled by event loop;
  5. Non blocking I/O
  6. The event loop works on single thread, but all long-running tasks (network I/O, data access, etc.) are always executed asynchronously on top of worker threads which return the results via callback to the event loop thread. That gives us asynchronous non-blocking way of handling code execution.

When you should use Node.js?

  • Data streaming - because of its asynchronous nature it's very good for handling real-time data streaming. It can be used to stream media, data from multiple sources, file upload or it's great for Websockets server;
  • API server - because it can handle many connections at once, it's well suited for an API service. The JSON format is used naturally by Javascript, therefore you can easily convert Javascript Objects into JSON format;
  • Microservices – Node.js is well suited to act as microservices server. Because it's fast and lightweight it can be used for writing microservices for example - API gateway.

Who uses Node.js?

Currently it used by almost EVERYONE! To name a few, it is used by big companies like:

  • Yahoo!
  • PayPal
  • Netflix
  • Medium
  • LinkedIn

How to start?

Getting started is very easy. First of all, you need to download Node.js. Remember to choose version the matches your system!

Installing Node.js

  • Windows

It's as simple as installing other Windows software. There's dedicated installer which you simply run and follow displayed instruction step by step.

  • Mac OS X

There's also .pkg standard installer for Mac OS X, which works similar to the Windows installation.

  • Linux

There are few options here. Most popular Linux distributions have Node.js in their package managers like apt-get or yum, which I recommend for less experienced Linux users. Whole process is described more thoroughly here.

Another option is to compile it yourself. Probably if you want to do that you will need some experience with Linux.

Generally you will have to run these commands:

sudo wget https://nodejs.org/dist/v5.4.1/node-v5.4.1.tar.gz
sudo tar -xzf node-v5.4.1.tar.gz
cd node-v5.4.1
sudo ./configure
sudo make
sudo make install

Last options is to download and use precompiled binaries. Same as above, an experienced user you should not have any problems with that kind of installation.

First steps

After the installation of Node.js, you need have node command available from your console.

To test if it's installed correctly, run:

node -v

Based on installed Node.js version, it should output something like:

v5.2.0

If not you probably have done something wrong - you should check if you properly completed all previous steps.

First program

Now I'll show you how to write simple HTTP server in Node.js. Let's create an file called server.js

// Import the HTTP module
var http = require('http');

// We define port to listen to
var PORT = 8080;

// Create a server and pass callback is called someone send an request
var server = http.createServer(function(request, response) {

// Send response to client and print an message
response.end('Your first HTTP server written in Node.js');

});

// Listen connections on port defined as PORT
server.listen(PORT, function() {

// Callback called when server is listening
console.log("Server listening on: http://localhost:%s", PORT);

});

Now you can simply run it by calling:

node server.js

After that the calling script should look similar to this:

> node server.js
Server listening on: http://localhost:8080

Now you can open URL in the browser http://localhost:8080 - it should print Your first HTTP server written in Node.js message.

Code analysis

Loading HTTP module

First of we need to import the http module, which is one of built-in core in Node.js. It also comes with https module for handling secured HTTP connections.

// Import the HTTP module
var http = require('http');

Creating a server and defining handler callback function

After that we need to call http module with createServer() method in order to create an server. This method takes an callback as an argument, which is our request handler. Request handler gets two arguments:

  • request - which is an object containing request information;
  • response -– which is an object which have properties and method to handle response for the client.

In that example we call end() method of response object, which ends connection and sends response to the client - in that case it's the simple plain text message.

// Create a server and pass callback is called someone send an request
var server = http.createServer(function(request, response) {

// Send response to client and print an message
response.end('Your first HTTP server written in Node.js');

});

Starting the server

To start our created server we need to execute listen method, which takes two arguments. The first one is a port to listen to, and second one is a callback function which is executed when server starts listening on that port. We used that callback to print messages that server is ready and information on host and port that server is listening to.

// Listen connections on port defined as PORT
server.listen(PORT, function() {

// Callback called when server is listening
console.log("Server listening on: http://localhost:%s", PORT);

});

Pros and cons of using Node.js

PROSCONSAsynchronous event driven IO helps concurrent request handlingAsynchronous programming learing curveWorks extremely fastAwful experience of the callback! We need to pass callback to almost every function (although there are some ways of avoiding that, like using Promises)Writing the code in JavaScript (Yay!)It’s not working well with CPU-intensive tasks.Big community NPM - big collection of ready to use community modules It’s battle tested (used by big companies) It’s great for real-time web

Summary

We need to be aware that each technology have their own pros and cons. I can't say that Node.js if perfect for every project, but it's great for many web solutions. Personally I love using Node.js and I use it everyday and I would highly recommend you to learn at least some basics.

If you want to learn more about web development, check out other articles on our blog!

Navigate the changing IT landscape

Some highlighted content that we want to draw attention to to link to our other resources. It usually contains a link .