Tuesday, May 10, 2016

Tutorials: NodeJS and Express (Tutorial 1)

Tutorials: NodeJS and Express

NodeJS Tutorial 5: Using HTTPS with Express

While learning about Express  and how to use, here is my small effort to document my learning in tutorial form. Express  has become an integral part in web applications developed in NodeJS.

Tutorial 1: NodeJS: An Asynchronous World
Tutorial 2: Express: Middleware or more...
Tutorial 3: Understanding Routing in Express
Tutorial 4: Develop a Static File Server
Tutorial 5: Using HTTPS with Express
Tutorial 6: Develop a JSON API server
Tutorial 7: Use Templates and Views with Express
Tutorial 8: Integrating MongoDB
Tutorial 9: Testing Express Applications
Tutorial 10: Securing Express

Tutorial 1: NodeJS: An Asynchronous World

For so many years, Javascript has been a defacto standard to do front end scripting in browsers. In 2009, another incarnation of JS (V8 JS engine from Chrome) as node.js came out which made it server side scripting language also. NodeJS came up with a bouqet of many features like:
  • Its execution is fast (V8 JS engine being compined in C++)
  • Promotes asynchronous coding style
  • Same coding paradigm for front and back end.
Its event-driven, non-blocking I/O model make it popular among developers community. NodeJS has assemblage of libraries and frameworks helping developer community. Express JS or Express is also one of the framework available for NodeJS helps in developing web based applications.

Installing NodeJS

The simplest way is go to NodeJS website and click on the installer link. The site also provides other download options (binary download or installers for Mac and Linux flavours). For Windows make sure your machine has latest OS updates otherwise windows installer may have trouble in installing.

Tutorials: NodeJS and Express (Tutorial 1)

For Linux, nodeJS package manager (eg apt-get) is also available. The installer also installs node package manager (npm). Once installed you can check node version and npm version by typing node -v and npm -v respectively at the command prompt or shell.

First NodeJS Program

You can try your first the most famous "Hello World" program in nodeJS. Type the following script in notepad or any text editor and save the file as helloworld.js

Program 1: helloworld.js

console.log("Hello World");

To run this code type node helloworld.js at the shell prompt. If everything works well, you would see the output of the program similar to what is shown in the figure.
Tutorials: NodeJS and Express (Tutorial 1) - Hello World

console.log() api is part of console built-in module in nodeJS. There are many inbuilt modules (or libraries) and globals defined in nodeJS. Apart from using built-in modules, you can use external modules.

Node Package Manager or npm helps you installing or managing node modules. The site www.npmjs.com lists the most starred packages used among NodeJS community.

Let us try to install and use colors module. The colors module gives colour style to your console output. Type npm install colors will download colors module from npm repository and install it. You can see a directory named 'node_modules' gets created where npm installs any package.

Tutorials: NodeJS and Express (Tutorial 1) - install color module
npm install color

See the following snippet showing how to use 'colors' node module:

Program 2: ex2.js

var colors = require("colors");
console.log('This is red'.red);
console.log('This looks green'.green);
console.log('this rainbow text'.rainbow);

The statement require("colors")in the above snippet will load the "colors" exported JavaScript API and returns the JS object. Once colors Javascript Object is loaded, you can call its exported functions and members in your program code. The output of the above snippet will look like the Figure

Tutorials: NodeJS and Express (Tutorial 1) - using color

Asynchronous Programming Approach

Asynchronous programming is another important aspect of NodeJS making it popular. Asynchronous functions take an additional argument(s) known as 'callback function' which are called when a particular event occurs. It is also called by another name 'continuation passing style' (CPS) programming. Let us write a simple nodeJS program to read a file asynchronously.
See the following snippet:

Program 3: ex3.js

/* read file contents asynchronously */
var colors = require('colors');
var fs = require ('fs');
fs.readFile('./poem.txt', 'utf8', function onread(err, data) {
   if (err) {
      throw error;
console.log("reading file...");

To read a file, we load another builtin node module 'fs' stands filesystem. This package provides File I/O routines available both synchronously and asynchronously.

The api fs.readFile reads file (named poem.txt) using UTF8 encoding. When its reading is complete, it invokes a callback function i.e. we call it onread( ). While the reading is going on, our program moves on to the next statement. That's why it displays "reading file..." message first. The call back function takes two parameters i.e. err and data. If there is an error in reading a file, it throws an error. Otherwise it displays the content using console.log( ).

Tutorials: NodeJS and Express (Tutorial 1) - read file

Write a simple nodeJS web Server

NodeJS has built-in module 'http' which can be used to develop a simple web application server. Let us write and save the following snippet and run the node program (eg node myserver.js).

Program 4: ex4.js

var http = require('http');
var server = http.createServer(function(req, res) {
 res.write('Hi! response from server.');
 var msg = '';
 if (req.method === 'GET')
    msg = 'GET method called.';
 else if (req.method === 'POST')
    msg = 'POST method called.';
 else if (req.method === 'PUT')
    msg = 'PUT method called.';
    msg = req.method + ' not supported.';


The first line loads 'http' built in node module. The second line createServer( ) creates a server object which listens for http requests at port 8080 (last line).

You can open a browser and type http://localhost:8080 to see the output. You will see server receives the connect event, it calls the callback function (line 3). The callback function has two arguments i.e. req (request object) and res (response object). As you know http communication is called request – response communication i.e. Browser (client) sends the request object and the server replies with response object (containing response headers and body text/binary). Here res.write (write method of response object) sends output string "Hi! Response from server".

The Line number  5,  req.method tells what type of HTTP request method (or verb) is used by the client. The most common HTTP methods are  GET, POST, PUT, DELETE and HEAD. Usually these correspond to develop read, create, update, delete (CRUD) etc. operations while developing WEB based APIs or services.

Let us write a small nodejs headless browser client which talks to our primitive server app. The node module 'http' also implements client communication.

Look at the following snippet which sends GET request to the server:

Program 5: ex5.js

var http = require('http');
var request = http.get('http://localhost:8080/', function(resp){
 resp.on('data', function(data){
 resp.on('end', function(){
  process.stdout.write('\nGET response ended');

The method http.get( ) sends a get request the server (here to localhost at port 8080) and waits for the response data as a callback.  When data is received, it displays using process.stdout.write method. You can use console.log( ) instead. The above snippet does not handle any error which may occur for different reasons e.g. Server is down.
Tutorials: NodeJS and Express (Tutorial 1)

Let us try another method http.request( ) which provides more control to http communication. In fact http.get( ) calls the default http.request( ).

Let us implement PUT request using http.request( ) method. Look at the following snippet.

Program 6: ex6.js

var http = require('http');

var reqData = "dummy";

var reqParams = {
 hostname: 'localhost', 
 port: 8080,
 path: '/',
 method: 'POST',
 headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': reqData.length

var req = http.request(reqParams, function(resp){
 resp.on('data', function(data){
 resp.on('end', function(){
  process.stdout.write('\nPOST response ended');

http.request( ) accepts different options such as:

hostname: It is the hostname or ip address of the server.

port:  port of the http server is listening to.

method: A string specifying HTTP verb. Its possible values can be GET, PUT, POST, DELETE etc.

path: requesting path of the url containing query parameters (if any).

headers: It is an object containing requesting headers as value name pairs. e.g. Here we use  Content-Type header to inform the server that client is submitting form data.

http.request( ) method returns a request object (here we call it req). The req.write( ) method sends the form data to the server and wait for the response. When server replies, response event is triggered and the callback in http.request provides you a response object (here we call it resp). In the 'resp' object, we register for “data” event to receive the response body or content.

Tutorials: NodeJS and Express (Tutorial 1)

HTTP communication is the central core of web services. I suggest learn about various http methods, request and response architecture. I suggest go to httpbin.org and which helps you test your http client communication nodejs code.

In the next tutorial, we'll learn about ExpressJS, a third party module which abstracts away lot of http complexity and helps you focus on writing business logic.

No comments: