Node.js - Quick introduction

Nov 12, 2017 A. Gomes Bluetooth, General


Node.js logo

The Axiomware netrunr-gapi-js JavaScript SDK offers easy-to-use libraries of classes and methods for developing Bluetooth applications. This SDK supports application development on any JavaScript platform. The most common example of a JavaScript platform is your internet browser (like Google Chrome, Microsoft Internet Explorer, Apple’s Safari or Opera).

JavaScript’s affinity for a browser in no accident. Netscape developed JavaScript as a scripting language for its browser. JavaScript is a high-level, interpreted programming language with support for event-driven methods. Browsers are a powerful platform for creating internet-centric applications with rich UI capabilities. JavaScript code in a browser operates seamlessly across operating systems and underlying hardware. Browsers are a great choice for user-centric, UI focused applications.

What are your options for server-centric applications? Node.js is becoming the de facto runtime for deploying server-centric JavaScript applications. This post will provide a quick introduction to Node.js.

What is Node.js?

Ryan Dahl created Node.js in 2009 by using the Google Chrome’s V8 engine, an event loop, and low-level I/O libraries. Node.js is designed to handle many concurrent tasks. Node.js does not follow the typical “Multi-threaded request-response” architecture to support large-scale concurrent processing. Node.js uses the “single-threaded event loop model” to handle concurrent tasks. The figure below illustrates Node.js architecture.

Node.js architecture

V8 JavaScript engine: This is a Just-in-Time (JIT) compiler for JavaScript developed by Google for the Chrome browser. V8 compiles and executes JavaScript source code, handles memory allocation for objects, and garbage collects objects it no longer needs. V8’s stop-the-world, generational, accurate garbage collector is one of the keys to V8’s performance.

Node-bindings: The libraries provide an interface between JavaScript calls and underlying library implementations in C or C++.

Libuv: This library manages all I/O operations and events in the event pool. This library is designed around the event-driven asynchronous I/O model. The library provides much more than a simple abstraction over different I/O polling mechanisms: ‘handles’ and ‘streams’ provide a high-level abstraction for sockets and other entities; cross-platform file I/O and threading functionality is also provided, amongst other things.

Node modules and NPM: Node.js has a set of built-in modules that do not require any further installation. In addition to these built-in modules, developers have published more than 600,000 node modules at https://www.npmjs.com, designed to provide additional functionality to your Node project. Node.js comes packaged with Node Package Manager (NPM). NPM is used to install and manage the node modules and other dependencies for your Node project. NPM has three distinct parts: 1) the website, 2) the command line tool and 3) the node package registry.

Getting started with Node.js

Installation

In this section, we will show you how to get started with Node.js. This will be useful if you want to try out some examples listed below. Node.js is available in source and binary form at https://nodejs.org/en/download/. For most users, we recommend the Long-Term-Support (LTS) version. Along with node.js, the NPM is also installed. You can check if you have installed the software properly by typing the following in a command prompt or in terminal window:

> node -v
v8.11.1
> npm -v
3.10.6

Initialize a Node application

NPM is used for managing node module dependencies. Use of NPM is not mandatory, but highly recommended. To start a new node app, create a new directory. Inside this new directory, run:

> mkdir mynodeapp
> cd mynodeapp
> npm init

For entry point, you can change it to nodeapp.js. You can use defaults for all other settings. This command will generate package.json file which stores all your settings and node project configuration. This file can be edited using any text editor.

Create a Node application

Next, create an empty text file, named nodeapp.js and add the following code.

var express = require('express');
var app = express();
var count = 1;

app.get('/', function (reqest, response) {
  reqest.send('Hello World! You are vistor #' +  (count++));
});

app.listen(8080, function () {
  console.log('Nodejs webserver listening on port 8080!');
  console.log('To see this webpage, go to http://localhost:8080 on your browser(on the same machine)');
  console.log('Enter CTRL-C to exit');
});

This JavaScript program starts a simple webserver that listens on port 8080. Any client that connects to this port will be served with a simple Hello World! You are vistor #... message. This example uses the Express web framework for Node.js. Since this framework is not a part of built-in modules, you must install it using the command below:

> npm install express --save

NPM will install all the dependencies required to run Express. You can open the package.json file and note the changes. You will also notice that a new directory node_modules has been created. All the files required for express are located inside this directory. If you delete node_modules directory, you can recreate it by running npm install. If you need to send your node.js program to someone, you only need to send the node.js source file nodeapp.js and package.json. The recipient will be able to recreate your node.js project.

Try out the Node.js app

To try out the new Node.js applications, type the following command:

> node nodeapp.js

Open a browser window on the same computer and open http://localhost:8080/ . You should see the simple hello world message. You can open multiple browser windows and single Node.js web server will be able to keep up with the load. Let us look at some of the details of this program:

var express = require('express');
var app = express();
var count = 1;

The require statement includes the express framework inside our program. We create two variables, count and app, where app is an instance of the express class.

app.get('/', function (reqest, response) {
  reqest.send('Hello World! You are vistor #' +  (count++));
});

app.get is an express method that sets the response of the webserver when a client requests the URL(\). The first argument of this function is the URL route. The second argument is an anonymous callback function:

function (reqest, response) {
  reqest.send('Hello World! You are vistor #' +  (count++));
}

This function is registered with the Node.js event processing system. This function is only executed when a URL request is made to this route. The only work done by the function app.get() is to register the callback function against the route.

The last part of the program executes the app.listen() function. This starts the webserver listening on port 8080. The second argument of this function an anonymous function that is executed after successfully starting the webserver.

At this point, all parts of the main program finish executing. If any client browser makes a request on port 8080, the Node.js event system will use the appropriate callbacks to service the request. Node.js also has a set default callback function to handle shutdown events like CTRL-C to handle graceful shutdown of the Node.js program. It is obvious that this architecture which is composed of an event system and light-weight callbacks has low computational overhead.

Going further

JavaScript is a fun language to learn. Over time, new versions of JavaScript have improved many facets of the langauage. The most recent version of JavaScript is called ECMAScript 6. This version incorporates improvements in variable scoping, support for promises and async/await, arrow functions and JavaScript generators. All these features improve power and useablity of JavaScript. There are many online resources for learning JavaScript and Node.js. Some of them are listed below:


JavaScript® is a trademark of Oracle Corp. Node.js® is a trademark of Joyent. Other trademarks and trade names are those of their respective owners.