Node.JS Domain Module

Unhandled errors can create some serious problems for the programmers. Node.js domain module detects and terminates these errors. It can use either external or internal binding to accomplish the task. The Node application will ultimately crash if you fail to handle these errors for an extended period of time.

  • Internal Binding: In this type of binding, error emitter executes its code inside domain’s run method.
  • External Binding: In this type of binding, you can use the added method to add error emitter exclusively to a domain.

You can use the following syntax to import this particular module.

var domain = require(“domain”)

The node.js domain module has its own domain class. The functionality of both undetected exceptions as well as routing errors is provided to active Domain object by this very domain class. It is generally known as EventEmitter’s child class. The basic function of the class is to catch errors. You must keep an eye on its error event to effectively handle these errors.

domain.run(function)

The easiest way to use any domain is to run this function inside the domain. Subsequently, you have to explicitly bind all low level requests, timers as well as EventEmitters generated within that domain.

domain.add(emitter)

In this particular method, you will implicitly add an error emitter to a domain. It works similarly to implicit binding. The code will route all the error events and errors generated by emitters and emitter handlers to the main error event of the domain.

domain.remove(emitter)

This method is exact opposite of domain.add. In this method, you remove domain handlers from a certain emitter.

domain.intercept(callback)

domain.bind and domain.intercept work almost on the same principle. However, domain.intercept also catches Error objects. These errors act as the first argumentation to the function.

domain.exit()

This method removes the current domain from domain heap by exiting the domain. It is imperative to exit the current domain whenever you have to execute a different series of asynchronous calls. The method also calls to exit input/output operations of a domain as well as delimits at the beginning of a series of asynchronous calls.

Take a look at the following example to see some of the aforementioned functions in action.

var EventEmitter = require("events").EventEmitter;
var domain = require("domain");

var emit1 = new EventEmitter();


var dom1 = domain.create();

dom1.on('error', function(err){
   console.log("Error handled by dom1 ("+err.message+")");
});


dom1.add(emit1);

emit1.on('error',function(err){
   console.log("listener handled this error ("+err.message+")");
});

emit1.emit('error',new Error('Listener will handle this'));

emit1.removeAllListeners('error');

emit1.emit('error',new Error('Dom1 will handle this'));

var dom2 = domain.create();

dom2.on('error', function(err){
   console.log("Error handled by dom2 ("+err.message+")");
});


dom2.run(function(){
   var emit2 = new EventEmitter();
   emit2.emit('error',new Error('Dom2 will handle this'));   
});


dom1.remove(emit1);
emit1.emit('error', new Error('Exception message...!'));

Download the code Try the code

Node.JS Packaging

Once you have completed your application, you need to package it to send to different machines. Node.js has JX core project which helps packaging of the application. Consider a scenario where you have node.js application written on multiple pages the JXCore project help you bundle all the modules in one. In this article we shall explain node.js packaging.

JXCore installation

Perform the following steps in order to download and install JXCode.

Step1

Download JXCore from this https://github.com/jxcore/jxcore-release. The version you installed depends upon your machine requirements. We shall explain installing JXCore for windows.

Step2

Open the rar file that you downloaded and copy and past “jx” application file to any folder. Set the path of that folder in your environment variable

Step3

Finally, to verify if JXCore has successfully been installed type “jx –version” on command prompt. It should display the version number.

Node.js Packaging Code

Now once you have successfully installed the JXCore module, you can package any code. Suppose you have fork.js and child.js files that you created in the node.js child process creation article. You want to package these two files.

To do so, simply go inside the directory that contains these two files and open command window here. We know the entry point of our code is “fork.js” because this is the parent process that calls the child process. Therefore, the command that you will use to package all the files in this directory will be “$ jx package fork.js fork”. We named “fork” at the end because this is the name with which the package file will be generated

If you run the above command, you will see two files generated in the directory: fork.jx and fork.jxp. Here the first file is what you need to ship to the client. It is the file package. The second file.jxp file is the file that contains meta data info.

Running JX File

Running JX file is very simple. Type the command “jx fork.jx”. This will execute the fork.jx file that contains your application.

Node.JS DNS Module

We have so far looked at many node.js modules such as express module, web module, path module etc. In this article we are going to study yet another module i.e node.js DNS module which provide underlying system’s name resolution and DNS look up facilities. DNS module consists of an asynchronous network wrapper. DNS module can be imported via “var DNS = require(“dns”)” command. Let’s have a look at some of the most commonly used DNS functions.

dns.lookup(adress, options, callback)

The dns lookup method takes any website address as its first parameter and returns the corresponding first IPV4 or IPV6 record. The options parameter can be an integer or object. If no options are provided both IPV4 and IPV6 are valid inputs. The third parameter is the callback functions.

dns.lookupservice(address, port, callback)

This function converts the address and port passed to it as parameters into host name and service name running at the port. It uses getnameinfo method to perform transformations.

dns.resolve(address, rrbytes, callback)

This function converts any physical address such as “www.knowledgehills.com” to array of record types. The record types are specified by the second parameter “rrbyte”. Finally the third method is the callback function.

dns.getServers()

This method returns list of all the servers that are currently being used to resolve client requests.

dns.setServers()

This method is reverse of the getServers method and is used to register all the IP addresses passed to it as resolution servers.

Take a look at the following example to understand node.js dns module lookup method.

var DNS = require('dns');

DNS.lookup('www.knowledgehills.com', function onLookup(err, address, family) {
   console.log('address:', address);
   DNS.reverse(address, function (err, hostnames) {
      if (err) {
         console.log(err.stack);
      }

      console.log('The reverse of  ' + address + ': ' + JSON.stringify(hostnames));
   });  
});

Download the code Try the code

Take a look at the above code, here we first import the required dns module via require(‘dns’) module. Next we used the dns.lookup() function and passed it “www.knowledgehills.com”. The callback function converts this hostname into IP addresses. Next we printed the reverse of the IP into domain name.

Node.JS Spawn-Fork Functions

In the previous article we started our discussion about child processes in node.js. We know that there are three ways of creating a child process via node.js child_process module: exec, spawn and fork. In last article we saw a working example of exec function for creating and running child process. In this article we shall discuss Node.JS Spawn-Fork Functions for creating child processes.

Spawn

The command for creating a child process via spawn is this: child_process.spawn(command[, args][, options]). Here first option is the command that you want to execute in the child process, the second parameter is the list of arguments in the form of array. We shall pass the name of the file here that we want executed in a separate process. Finally the third parameter is the set of options that you can pass to the process. We shall pass only integer which sets the id of the process. Take a look at the following example.

First create a file named “child.js” and add the following line of code to it
console.log(“Child process with id ” + process.argv[2] + ” completed execution.” );

The following is the code for parent.js file that contains parent function.

const cld_proc = require('child_process');
 
for(var i =1; i<=5; i++) {
   var parentProcess = cld_proc.spawn('node', ['child.js', i]);

   parentProcess.stdout.on('data', function (data) {
      console.log('stdout value: ' + data);
   });

   parentProcess.stderr.on('data', function (data) {
      console.log('stderr value: ' + data);
   });

   parentProcess.on('close', function (code) {
       console.log('Child process is exiting with exit code: '+code);
   });
}

Download the code Try the code

The spawn function relies on event rather than callback as was the case with exec. Whenever a child process completes execution the stdout eventEmitter generates data event which contains the output for the child process. In case of error the on event of stderror is generated and handled accordingly.

Fork

Fork is a type of spawn and is another way of generating child process in node.js.

The command for creating a child process via spawn is this: child_process.fork(modulePath[, args][, options]). Here first option is the path of the module that you want to execute. This is in string form. The first parameter is optional. The second parameter is the list of arguments in the form of array. We shall pass the name of the file here that we want executed in a separate process. Finally the third parameter is the set of options that you can pass to the process. We shall pass only integer which sets the id of the process. Take a look at the following example.

First create a file named “child.js” and add the following line of code to it
console.log(“Child process with id ” + process.argv[2] + ” completed execution.” );

The following is the code for parent.js file that contains parent function for fork.

const fileSystem = require('fs');
const cld_proc = require('child_process');
 
for(var i=1; i<=3; i++) {
   var parent_process = cld_proc.fork("child.js", [i]);	

   parent_process.on('close', function (code) {
      console.log('Child process is exiting with exit code: '+code);
   });
}

Download the code Try the code

Node.JS Child Process Creation

Since first tutorial of this series, we have been saying again and again that node.js applications are single threaded. In node.js multitasking is performed via events and callbacks. However, in addition to these features you can utilize CPU’s multiple cores by assigning the child processes. Yes, node.js contains child processes. In this and the following article we shall study node.js child process creation.

Child_process Module

Node.js child process creation involves using child_process module. There are three ways that can be used to create child processes via child_process module. They are as follows:

  • exec: This function runs in a shell or command prompt and stores output in a buffer.
  • spawn: This function creates a totally process via command prompt.
  • fork: It is a type of spawn function and is used to create new process as well.

Creating Child Process via exec

The syntax for creating child process via exec is simple. You have to use child_process.exec(command[, options], callback). Here first option is the command that you want to execute in the child process, it can be running some file etc. The second parameter is the set of options that you can pass to the process. We shall pass only integer which sets the id of the process. Finally, the third option is the callback function with three parameters: error, stdout, stderr. Take a look at the following example to understand how exec works.

First create a file named “child.js” and add the following line of code to it

const fileSystems = require('fs');
const cld_proc = require('child_process');

for(var i=1; i<=5; i++) {
   var parentproc = cld_proc.exec('node child.js '+i,function 
      (error, stdout, stderr) {
      
      if (error) {
         console.log(error.stack);
         console.log('Error Code: '+error.code);
         console.log('Reason of error: '+error.signal);
      }
      console.log('Stdout value: ' + stdout);
      console.log('Stderror value: ' + stderr);
   });

   parentproc.on('exit', function (code) {
      console.log('Child process is exiting with exit code: '+code);
   });
}

Download the code Try the code

Take a careful look at the above code. Here we use a for loop that executes five times. In each iteration we call child_process variables exec method. The first parameter is the command to run, here we pass the command to run the child.js file we created earlier. The second parameter is the id of the process while the third function is the callback. Inside the callback function, if error occurs during child process execution we print that. Else we print the output of the child process via stdout. Finally we print the code with which child process exited.

In the next article, we shall how to create child process via spawn and fork.

Node.JS Path Module

The previous article explained what OS module is and how it can be used to get information regarding the underlying OS. In this article we are going to study node.js path module which is yet another extremely handy module when it comes to performing path related operations such a resolving a relative path to its absolute path, checking whether a path is absolute or not, joining multiple path, getting directory name from path and finding file extensions. Following are some of the most useful functions in node.js path module.

  1. path.normalize(p): This function normalizes the path passed as parameter by taking care of . and .. etc.
  2. path.join(p1,p2,p3 …): This function joins all the paths passed to it as a parameter and returns the normalized joint path.
  3. path.resolve(p): It resolves the path any path passed as parameter to its complete absolute path.
  4. path.isAbsolute(p): Returns true if the path passed to the function is an absolute path.
  5. path.extname(p): This function returns the extension name of the file in the last part of the path. If the file doesnt contain a “.” then the function cannot calculate the file name. Rather it returns an empty string.

Node.js Path Module Example

To see all the path functions discussed above in action, take a look at the following example. Create a file named pathmodule.js and add the following code to the file.

var pathmod = require("path");


console.log('Normalization funcion : ' + pathmod.normalize('/path/path2//path2slashes/path3/tab/..'));


console.log('Join Path Funcion : ' + pathmod.join('/path1', 'path2', 'newpath/path3', '..'));

console.log('Resolve Function : ' + pathmod.resolve('pathmodule.js'));

console.log('Extension name function : ' + pathmod.extname('mainmodule.js'));

Download the code Try the code

Take a careful look at the above code. Your results might be different depending upon the path values that you have used. However, the first function simply returns the normalize path without double slashes and dots etc. The function joins all the paths passed to it and returns a single path. The resolve function returns the absolute path of the file “pathmodule.js”. Similarly the last function i.e. extname returns the extension of the file “pathmodule.js” i.e. “js”.

Node.JS OS Module

In the recent articles we studied node.js web module and then express framework. We also studied how express module is helpful in implementing the RESTful API. In this article we are going to briefly review Node.JS OS module. This module contains functions that are helpful in obtaining operating system related information. For instance, you can get OS name, OS architecture, the total amount of OS memory, the amount of free memory etc. Following are some of the most commonly used node.js OS module functions.

  • os.type(): It returns the name of the operating system.
  • os.platform(): Returns the platform of the operating system.
  • os.arch(): Returns the CPU architecture of the operating system for instance x86, x64 etc.
  • os.uptime(): Returns the total time since operating system has been up.
  • os.release(): Returns the release time of the operating system.
  • os.cpus(): Returns detailed information regarding all the cores installed on the system e.g speed,model and time.
  • os.totalmem(): Returns the total amount of memory of the system in bytes.
  • os.freemem(): Returns the total amount of free memory of the system in bytes

Node.JS OS Module Example

We have defined the usage of the most commonly used methods of OS module. Let’s see their working in action with the help of an example. Take a look at the following piece of code.

var os = require("os");




console.log('OS Type : ' + os.type());


console.log('OS platform : ' + os.platform());


console.log('OS Archi : ' + os.arch());


console.log('OS Uptime : ' + os.uptime() );


console.log('OS Release : ' + os.uptime() );

console.log('OS free memory : ' + os.freemem() + " bytes.");

console.log('OS Total memory : ' + os.totalmem() + " bytes.");

Download the code Try the code

The output of the above code depends upon the operating system on which the code is running. However, on my system the first function returns Windows_NT, the platform is Win32 and the architecture is X64. This means that I have a 64 bit windows operating system running on my machine.

OS module is extremely helpful in those cases where you program same application for multiple operating systems. You can place checks which implicate that if the underneath operating system is windows, do this else do that. In the next article, we will study path module in detail.

Node.JS Express Framework II

This is the second part of the article on node.js express framework. If you havent read the first part, I would advise you to check that article first and then come back and study this article. In previous article we saw how to send response back to an HTTP request. Apart from that you can also send static resources such as images, javascript files and stylesheets. Suppose you placed your images in a folder named “images” in the root directory. You can provide access to this directory via “expapp.use(express.static(‘images’))” command. Take a look at the following example.

var express = require('express');
var expapp = express();

expapp.use(express.static('images'));

expapp.get('/', function (req, res) {
   res.send('Welcome to knowledge hills');
})

var rserver = expapp.listen(9006, function () {
   var hostaddr = rserver.address().address
   var portaddr = rserver.address().port

   console.log("Server running at http://%s:%s", hostaddr, portaddr)

})

Download the code Try the code

In the above example we used express.static(“images”) middleware command and pass it the path that we want to be accessible by the client. Now anything inside the “images” folder is directly accessible via URL. Remember to test this example, create a folder named images inside the directory that contains your code file. The folder “images” and your code file should be at same level inside the directory. Now place any image named “pic1.jpg” inside the “images” folder. Type the following url in your browser “http://127.0.0.1:9006/pic1.jpg”. You shall see the image within your browser.

Handling Get Request From Forms

Till now, we have been hand coding the path in the browser to which server sends a response. However, we can also create form, fill some data in the form and then generate request via that form. The node.js server created via express framework shall also respond to that. Create a file named “main.htm” with following html script.

<html>
   <body>
      
      <form action = "http://127.0.0.1:9006/process_student" method = "GET">
         Student Name: <input type = "text" name = "student_name">  <br>
         Student Age: <input type = "text" name = "student_age">
         <input type = "submit" value = "Submit">
      </form>
      
   </body>
</html>

Download the code Try the code

Notice that in the above form the method used is GET and the URL in the action is 127.0.0.1:9006/process_student. Now you need to create node.js express app that can handle requests at this URL, and process them. The following code, simply display the name and age of the student passed via form, on the resultant web page. Take a look at the following code.

var express = require('express');
var expapp = express();

expapp.get('/process_student', function (req, res) {
   // Prepare output in JSON format
   response = {
      student_name:req.query.student_name,
      student_age:req.query.student_age
   };
   console.log(response);
   res.end(JSON.stringify(response));
})

var rserver = expapp.listen(9006, function () {
   var hostaddr = rserver.address().address
   var portaddr = rserver.address().port
   console.log("Server running at http://%s:%s", hostaddr, portaddr)

})

Download the code Try the code

Run the above code. And then fill the form that takes student name and age as input. Submit the form. A page shall open that will contain name and age entered by you in form. This shows that we have successfully created a node.js express framework app that listens to get request generated via form.

Node.JS Express Framework

In the article on NPM, we explained how NPM can be used to import online modules. As an example we download the express module. In this article we are going to study that express module in detail. Node.js Express framework is one of the most widely and frequently used frameworks. It contains functionalities that foster rapid development of web and mobile applications. The two major functionalities that node.js express framework provide are the ability to provide middle wares that can interact between HTTP requests and responses and the ability to render dynamic pages based upon user requests. Enough of theory, let’s create a simple node.js express framework application that returns welcome message to the user.

Node.js Express Framework Hello World Example

If you dont have express framework installed, type the following command in your node.s command window “npm install express –save”. Now let’s create a simple application that uses node.js express framework.

var express = require('express');
var expapp = express();

expapp.get('/', function (req, res) {
   res.send('Welcome to knowledge hills');
})

var rserver = expapp.listen(9006, function () {
   var hostaddr = rserver.address().address
   var portaddr = rserver.address().port
   
   console.log("Server listening at http://%s:%s", hostaddr, portaddr)
})

Download the code Try the code

Take a look at the above code. Here we again use the “get” method of the express class. This method takes the the path as the first parameter. The second parameter is the callback function that executes whenever a user requests for that path. In this case the path is the root folder which contains the code. For instance run the above code and then type the following URL in the browser “http://127.0.0.1:9006/”. This will display the message “Welcome to knowledge hills”

Basic Routing in Express Framework

In the last example we had a get method that displayed a simple string whenever a user requested for home page.The real beauty of express framework is the use of different HTTP methods and multiple paths. Take a look at the following example.

var express = require('express');
var expapp = express();



expapp.get('/list_student', function (req, res) {

   res.send('Page Contains List of All Students');
})

expapp.get('/ab*cd', function(req, res) {   
   res.send('Request arrived for abXcd. Where x can be anything');
})

var rserver = expapp.listen(9006, function () {

   var hostaddr = rserver.address().address
   var portaddr = rserver.address().port

   console.log("server running at http://%s:%s", hostaddr, portaddr)
})

Download the code Try the code

In the above code, there are two get methods. The first get method has a path “/list_student”. This method shall execute when user enters “http://127.0.0.1:9006/list_student” in the browser. Similarly, the second get method has a path “/ab*cd”. This method shall execute when user enters path that starts with “ab” and ends with “cd”. There can be anything between them

Node.JS RESTful API II

In the previous article, we started discussing node.js RESTful API. We saw what RESTful API is and how to implement HTTP methods to access RESTful API resources. We created a sample student database in JSON in the form of students.json file. We then used express module’s get function to create RESTful API’s listStudents method which retrieved list of all the students. However, we did not implement the addStudent, deleteStudent and :name methods. In this article we shall implement these methods.

AddStudent Method

It is very straight forward to add a user to already populated JSON database. Take a look at the following code snippet.

var express = require('express');
var expapp = express();
var fileSystem = require("fs");

var Student = {
    "Student5" : {
      "name" : "Wasim",
      "Age" : 12,
      "Gender" : "Male",
      "id":5
   }
}

expapp.get('/addStudent', function (req, res) {
  
   fileSystem.readFile( __dirname + "/" + "students.json", 'utf8', function (err, data) {
      data = JSON.parse( data );
      data["Student5"] = Student["Student5"];
      console.log( data );
      res.end( JSON.stringify(data));
   });
})
var server = expapp.listen(9006, function () {
   var host = server.address().address
   var port = server.address().port
   console.log("Server running at http://%s:%s", host, port)
})

Download the code Try the code

Take a look at the above code. Here we again use the “get” method of the express class. This method takes the the path of the RESTful method i.e. “/addStudent” as the first parameter. The second parameter is the callback function that executes whenever a user requests for “/addStudent” path. Notice that in the code we have created a new student object i.e. “Student5”. When a user requests for “/addStudent” path. The “Student5” object is added to the student database which is consequently printed on the screen. Run the above code and then type the following URL in your browser “http://127.0.0.1:9006/addStudent”. You shall see five students printed on the screen.

Show Student Method

The code for displaying detailed record of a student based upon the “id” attribute is as follows:

var express = require('express');
var expapp = express();
var fileSystem = require("fs");

expapp.get('/:id', function (req, res) {
 
   fileSystem.readFile( __dirname + "/" + "students.json", 'utf8', function (err, data) {
      data = JSON.parse( data );
      var student = data["Student" + req.params.id] 
      console.log( student );
      res.end( JSON.stringify(student));
   });
})

var server = expapp.listen(9006, function () {
   var hostaddr = server.address().address
   var portaddr = server.address().port
   console.log("Example app listening at http://%s:%s", hostaddr, portaddr);
})

Download the code Try the code

Take a look at the above code. Here we again use the “get” method of the express class. This method takes the the id of the student i.e. “/:id” as the first parameter. The second parameter is the callback function that executes whenever a user requests for “/id”. Inside the function, the details of JSON’s Student object whose value for id attribute matches the id passed in the path, shall be displayed. For instance run the above code and then type the following URL in the browser “http://127.0.0.1:9006/3”. This will display the record of student with id 3.

Delete Student

The following code deletes student with id three from JSON student data. Take a look at it.

var express = require('express');
var expapp = express();
var fileSystem = require("fs");

var id = 3;

expapp.get('/deleteStudent', function (req, res) {
   fileSystem.readFile( __dirname + "/" + "students.json", 'utf8', function (err, data) {
      data = JSON.parse( data );
      delete data["Student" + id];
       
      console.log( data );
      res.end( JSON.stringify(data));
   });
})

var rserver = expapp.listen(9006, function () {
   var hostaddr = rserver.address().address
   var portaddr = rserver.address().port
   console.log("Server running at http://%s:%s", hostaddr, portaddr)
})

Download the code Try the code

Run the above code and then type this url in the browser: “http://127.0.0.1:9006/deleteStudent”. You will not see student with id 3, among the students record.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .