Inheritance in Node.js

Read other posts on Node.js here

In this post we will take a look on inheritance of objects in Node.js. We will learn to use utility module to achieve inheritance in Node.js. However keep in mind that you can write plain JavaScript to achieve inheritance in Node as well. You can use Object.create() to inherit one object to another in Node.js also.

In this post we will learn to use util module to achieve inheritance in Node.js. Very first you need to import util module in your application

image

After importing util module, let us say you have an object as below,


function Student()
{

 this.name = "G Block";
 this.age = 40;
};

Just for demonstration let us add function in object using prototype,


Student.prototype.Display= function(){
 console.log(this.name + " is " + this.age + " years old");
 };

Next we are going to create ArtsStudent object which will inherit Student object.


function ArtsStudent()
{
 ArtsStudent.super_.call(this);
 this.subject = "music";
 };

util.inherits(ArtsStudent,Student);

Second line of code in ArtsStudent object is very important,

image

If you don’t call constructor of parent object as shown in above code snippet then on trying to access properties of parent object will return undefined.

In last line ArtStudent inherits Student using util.inherits() function ,

image

Next you can create instance of ArtsStudent and call function of parent object as below,


var a = new ArtsStudent();
a.Display();

Inheritance can be chained to any order. If you want you can inherit object from ArtsStudent as well. Inherited object will contain properties from both ArtsStudent and Student objects. So let us consider one more example,


function ScienceStudent()
{
 ScienceStudent.super_.call(this);
 this.lab = "Physics";
}

util.inherits(ScienceStudent,ArtsStudent);
var b = new ScienceStudent();
b.Display();

In above example ScienceStudent object inherits both Student and ArtsStudent objects. In this way you can work with inheritance in Node.js using util module. I hope you find this post useful. Thanks for reading.

Getting started with Node.js development in Visual Studio

Setup Environment on Windows machine for Node.js Development [Set up Sublime Text]

Yes you love node.js. You love event driven development and yes multi thread is old fashioned now. Your new found love is ASYNCHRONOUS. Asynchronous everything, even reading file system. As all we know Microsoft loves Developers. So in Build they decided to give node.js development support in Visual Studio 2012 and Visual Studio 2013.

In this post we will take step by step look on setting up Visual Studio for node.js development. You need to follow below steps,

Step 1

Download in install Node.js from http://nodejs.org/

Step 2

Next download and install Node.js for Visual Studio from here,

https://nodejstools.codeplex.com/releases/view/114437

You need to make sure that you select correct option to download. I am going to install Node on Visual Studio 2012.

image

After successful installation you will get below confirmation message of successful installation.

clip_image001[6]

 

After installation above said pieces you are good to go and start developing Node.js in Visual Studio. On launching Visual Studio in JavaScript language category, you will get various project templates related to Node.js

image

There are five different project templates available.

image

You can create Node.js application web based by selecting, Blank Node.js Web Application project template.

clip_image002

On successful creation of project you will get following files in project. Solution explorer will look like below,

clip_image003

server.js will contain code and entry point of application. By default server.js contains following code

clip_image002[6]

You just need to press F5 to run with debug or Ctrl+F5 to run without debugging. This default code will give you following output in browser

clip_image003[7]

And whereas debugger is listening on port 5858.

image

So we experienced that working with Node.js in Visual Studio is very smooth. You just need to press F5 to run application and can put a breakpoint and debug the code. As you see in below image that breakpoint is being hit.

image

You can find that intellisense will work as expected. This completely support intellisense for Node.js

image

Other thing you will notice that Node.js debugger support complete stack trace.

 

clip_image002[8]

 

Exporting existing Node.js project

You can create existing Node.js project from existing Node.js project by creating a project choosing template From Existing Node.js code

clip_image002[10]

On next screen you need to browse to existing project folder. You can also select files types to be included. After providing these two input click on Finish.

image

You will find existing project has been exported to new project.

In this way you can set up Visual Studio 2012 to work with Node.js development. I hope you find this post useful. Thanks for reading.

How to access functionality from various JS files in Node.js

In this post we will take a look on working with different JS files in Node.js. To start with let us assume a scenario that you have several js files and you need to work with these js files and use functionalities from these files in server.js.

In Node a JS file is a module. So to work with one file in another you need to load the module. For example if you want to work with A.js in server.js then you need to load A.js in server.js using require.

image

Let us assume that we have a file or module names Product.js as below.


var product =
{
 productName : "Pen",
 productPrice : 200,
 productStock : false
};

Now let us say we need to export

  • Product price
  • Product name

Export can be done using module.exports. So productName and productPrice will be exported to other modules as productname and productprice.

clip_image002

Here we are not exporting productStock. Product.js can be modified with export as below,

var product =
{
 productName : "Pen",
 productPrice : 200,
 productStock : false
};

module.exports.productname = product.productName;
module.exports.productprice = product.productPrice;

As of now export is done. Next to work with Prdouct.js module in any other files(module) we need to load it. So this can be loaded in server.js using require

clip_image002[6]

After loading module in product variable, you can access productname as

clip_image004

In Server.js productprice and productname from Product.js can be fetched as below,


var product = require('./product');
var pname = product.productname;
console.log(pname);
var pprice = product.productprice ;
console.log(pprice);


In output you should get productprice and proudctname printed. If you try to access productstock you will get error since this is not exported.

I hope you find this post useful. Thanks for reading.

Working with OS Module in Node.JS

In this post we will take a quick look on OS module in Node.js. OS module is to work with OS component. It provides some functionality to work with Operating System. Using this module you can get following information like below,

  • OS target version
  • Host name
  • OS temp folder
  • Total memory in system
  • Free memory in system
  • Load on system etc.

To work with os module you need to load the module first. You can load module as given below,

clip_image001

After loading os module you can use it to display operating system temp directory as below,

clip_image002

You can access host name as following,

clip_image003

You can access total memory and free memory as below,

clip_image004

You can access OS type and platform as below,

clip_image005

You can fetch CPU information as below,

clip_image006

Node will return output as below,

clip_image008

We saw that os module is very important to fetch information about operating system. Putting all together you can get various os information as below,


var os = require('os');
console.log(os.hostname());
console.log(os.totalmem());
console.log(os.freemem());
console.log(os.tmpdir());
console.log(os.uptime());
console.log(os.type());
console.log(os.platform());
console.log(os.cpus());

I hope you find this quick post on Node os module useful. Thanks for reading.

Events in NodeJS : Write your first event

Setup Environment on Windows machine for Node.js Development: Part 1

Let us simplify “Hello World” Node.js Example and EventLoop : Part 2

Each objects in NodeJS emit an asynchronous event. That event is handled by an object EventEmitter. EventEmitter is underneath every object.

EventEmitter object,

  1. Takes care of event being emitted by Node object
  2. Handles events emitted by Node object

EventEmitter object provides asynchronous event handling to Node object.

Now let us use how we can create a simple event. To create and event you need to follow following steps to create an Event in Node

Load events module. You can load that as follows,

image

After loading events module you need to create instance of EventEmitter. This can be done as follows,

clip_image001

Now you can attach an event using on eventhandler and emit an event using emit eventhandler. There are two steps involved in creating an event.

  1. Attach
  2. Emit

You can attach an event using on event handler. You can emit an event using emit event handler.

clip_image001[6]

To attach an event you need to call on method. This takes two parameter.

  1. Name of the event
  2. Functions to be called when event will be emitted.

You can add an event as follows. As you see there are two parameters. ‘error’ is name of the event and errorFunction is function called when error function emits on myLogger.

clip_image001[8]

In last step you can emit an event as follows. You need to pass event name and message(if any) to function.

image

Putting all together you can create an object and add error event to that as follows,

 


var events = require('events');

var myEvents = events.EventEmitter;
var myLogger= new myEvents();

myLogger.on('error',errorfunction);
function errorfunction(message)
{
 console.log(message);
}

myLogger.emit('error','hey I am an Error');
myLogger.emit('error','hey I am not an error but still');

 

Expected output is as follows,

clip_image001[10]

In further posts we will get into details of events in NodeJS. I hope you find this post useful. Thanks for reading.

Let us simplify “Hello World” Node.js Example and EventLoop

We are learning Node together. In last post We Setup Environment on Windows machine for Node.js Development. We also wrote a Hello World program to verify whether environment is setup as expected or not. In this post we will try to understand each line of Hello World program. Understanding of this is very useful for better grip on complex topics of Node.

Yes when we start learning any new programming language, first program we write to print Hello World. I did the same when started learning Node.

Our Hello World program was as follows,

Server.js

image

Let me try to explain you above program line by line.

Line 1

In this line we are acquiring a package. To work with HTTP request, response and creating servers you need http package loaded into program. You can load that using require. You need http package to perform http operation and create server. Another example could be, if you are working with file system then you will have to load fs package. So as first line of code we loaded http package.

Line 2

In Line 2 we are creating Server. Server is created using createServer function. It takes an anonymous function as parameter. There are two parameter to anonymous function

  1. Server request : http.ServerRequest
  2. Server response : http.ServerResponse

Line 3

In Line 3 we are writing response header. Response header can be created using method writeHead. This takes following parameter

  1. Status code. In this case we have set it as 200.
  2. It takes a JSON object as optional second parameter. In this you can construct other response header information like
  1. Content length
  2. Content Type
  3. Connection
  4. Accept type

So you can construct header with above information as below,

image

Line 4

Line number 4 can be written in different ways. ServerResponse.end indicates the communication has been finished. It takes optional two parameters.

  1. Data in form of either string or buffer
  2. If Data is string then second parameter is encoding. Default encoding is utf8

In this case we are passing string to client in ServerResponse.end . Other way to pass data is using ServerResponse.write. If you use ServerResponse.write() then you will have to explicitly close communication using ServerResponse.end() without any value for parametres.

Line 5

In Line number 5 createServer() method is finished with chained http.Server.listen() method. This method specify

  1. Port number on which incoming request will be heard
  2. Optional host name.

Line 6

Printing message using Console object.

We need to understand that Unlikely other web servers Node works on single process. It handles all the requests ASYNCHRONOUSLY on the same process. It does not create new Process or spawn new Thread for each request. You can say Node is single Process web server with many Asynchronous events. Let us put in step by stop that how Node works. There are two concepts you should know to understand working of Node.

image

Node keep poling for events in Event Loop. When it gets an event it process that asynchronously and assign a Callback to this. You can say Calllback is a function which act as Event Listener and get fired on the complete of an event. Node never waits for an event to complete. It assign event request to a EventListener . EventListener or CallBack get executed once event execution is complete.

To summarize Node always works on Single process and execute each request asynchronously. I hope you find this post useful. Thanks for reading.

Setup Environment on Windows machine for Node.js Development

I am aspired to learn Node and I had tough time setting up environment for Node development. Guess what I got none other than Mr Glenn Block to help me. We did pair programming over Google Hangout and he helped me setting up. It was his kindness that he spent time with me. He has been inspiring many like me and helping developers around. He has done great work on Node and you can read few of his learning material at below link,

https://github.com/glennblock/node-azure-workshop/blob/master/part1_basics_01.md

This blog post is dedicated to Glenn. Language of this blog post is in the way that I am talking to you however this blog is just text version of Glenn work done with me while doing pair programming.

Yes I know you are excited for Node.JS. You know Node runs your script at server rather at the client browser. Cool, now let us see how we can set up development environment for Node development. You have choice to use any text editor of your choice to work with Node. I am choosing Sublime Text 2 as editor to write code. So put your sleeves on and follow following steps to set up environment.

Step 1: Download and Install in Node.JS

Navigate to http://nodejs.org/ and click on download.

clip_image002

You will be navigated to download page. From here select required installer, download that and then install that. I am working on Windows machine so I selected option of Windows Installer.

After successful installation go to shell and verify successful installation. To verify it type npm on command prompt and you should get output as given below. It also verify that node is successfully added to the path.

clip_image004

There is another option to install node as well. You can install it from chocolatey.

http://www.chocolatey.org/packages/nodejs.install

Step2: Install Sublime Text

As we discussed in beginning of this post, you can work with any text editor of your choice to work with Node. We selected Sublime Text. You can grab sublime from here

http://www.sublimetext.com/2

After downloading and installing navigate to https://sublime.wbond.net/installation#st2 . From here you need to install package in Sublime Text. Choose package for installed sublime text version. In my case it is Sublime Text2. Copy text for package from here.

clip_image002[6]

Now launch Sublime Text and open console. To open console you have two options

  1. View-> Show Console
  2. Type shortcut ctrl + `

On console paste copied text from previous step and press Enter. After package got installed we need to enable node package on Sublime Text. To enable this go to Tools-> Command Palette(Ctrl+ Shift+P) and search Node and install.

Once this is done you need to create working folder. You can create working folder anywhere. I have created a folder named NodeCodes in C drive. After creating folder we need to add folder to project. To do this navigate to Project -> Add Folder to Project. I have added NodeCodes folder as project.

clip_image001

Now you are good to go and environment for Node development has been setup at your machine.

Write Hello World and Run it

Now go ahead and create a file named Server.js in your working folder. In my case it is NodeCodes folder. In Server.js write below code. In further posts we will go into detail of these codes. As of now just copy paste them to run your first Node program.

Server.js


var http = require('http');
http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Now to run this go to command prompt and type Node Server.js . If you are not in working folder then do not forget to pass full path of Server.js

clip_image001[5]

As output you should get server running message.

clip_image002

Once you get this output means your development environment is up and you are good to play around Node. In further post I will discuss other topics of Node and try to simplify Node learning. Once again Thanks to Glenn for his support.