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.

Can you answer these 10 basic Knockout Questions?

Q1. KO performs following operations

 

  1. Automatic Refresh
  2. Two way Binding
  3. Templating
  4. All of the above

 

Q2. On which event bindings in KO fire notification

 

  1. Change event
  2. Update event
  3. On Any event
  4. None of the above

 

Q3. Value of computed observable is determined at

  1. Time of creation
  2. Time of update
  3. Time of DOM loading
  4. Depends on implementation

 

Q4. ko.toJSON is used for following purpose

 

  1. convert objects that include observables to a JSON string
  2. to convert string to object
  3. to consume JSON service
  4. to consume any service

 

Q5. How we can add reference of KO in project

 

  1. using local reference
  2. using CDN
  3. using Nuget package
  4. all of the above

 

Q6. On which value of ViewModel property visible binding will be set to block?

 

  1. Null
  2. Undefined
  3. Zero
  4. All of the above

 

Q7. ViewModel can be created as

 

  1. Object literal
  2. Function
  3. Both
  4. None of the above

 

Q8. Click binding can be bind to what kind of property in ViewModel

 

  1. Function
  2. Boolean
  3. Array
  4. All of the above

 

Q9. For what purpose we use foreach binding in KO

 

  1. To duplicates section of markup for each entry in array
  2. To duplicates section of markup for each entry in ViewModel
  3. To duplicates section of markup for each entry in Model
  4. None of the above

 

Q10. The Value binding should be used with

  1. <input> , <select> , <textarea>
  2. <span>, <div>
  3. <radiobutton> <table>
  4. All of the above combination

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.

Create your First MVVM based JavaScript App in two simple steps using Knockoutjs

Read all Knockoutjs posts here

Setting up Visual Studio 2013 for Knockoutjs Development

Okay purpose of this post is very simple to explain you why Knockoutjs. I will try to put it in simplest way that Why we need to work Knockoutjs. If you are not a begineer then probably this post may appear very simple to you. However I request keep reading this post.

Without Knockoutjs

Let us start with an application as given below. Application got two input box and a span to display a message.

image

Requirement of this application is as follows ,

  • Pull data from a data source. In this scenario data source is a plain JavaScript object.
  • Create a custom message.
  • Display message in label.
  • When data changes in input boxes notify back to data source.

Let us do it using jQuery and without Knockoutjs. Above view can be created simply as below,



 <h1>KO Demo</h1>   
     <span id="spnProductName">Product Name</span> <input type="text" id="txtProductName" />
     <span id="spnProductPrice">Product Price</span><input type="text" id="txtProductPrice" /><br />
    <h2> <span id="spnMessage"></span> </h2>   


A datasource can be created as plain JavaScript object. This can be created as below,


  var Product =
        {
            productName: "Pen",
            productPrice: 200
        };

Next we need to bind this data to input boxes element on DOM. This can be done using jQuery selectors. We need to select elements and assign values to elements.


    $("#txtProductName").val(Product.productName);
    $("#txtProductPrice").val(Product.productPrice);
    var message = Product.productName + " costs " + Product.productPrice;
    $("#spnMessage").text(message);


In above code snippet we are creating a custom message reading values from JavaScript object and then assigning that to span element on DOM.

This is what all we need to do. When you run application you should get elements are prepopulated with data from JavaScript object.

clip_image001

One major problem in above implementation is that if you change Product Name or Product Price, it will not get notified to data source. Here you are pulling data from the data source and there is no binding between elements and data source.

In simple words when you change value of Product Name or Product Price custom message will not change by default. Off course you can implement it using jQuery but that would be complex.

With Knockoutjs

Now let us implement above requirement using Knockoutjs. In Ko we need to create

  • Model
  • ViewModel
  • View

In this requirement we will create only ViewModel and View.

Step 1: Creating View

A View is nothing but HTML elements. So we can reuse view used in above example. But we need to use data-bind attribute of HTML5 to bind data from data source. For example if you want to display (bind) Product Name in first input box. To do this we will bind value attribute to productName (this is property representing Product Name in ViewModel)

image

We can create complete View of application as below,



<h1>With KO</h1>
     <span id="spnProductNamek">Product Name</span> 
    <input type="text" 
          id="txtProductNamek" 
           data-bind="value:productName" />

     <span id="spnProductPricek">Product Price</span>
    <input type="text" id="txtProductPricek" 
        data-bind="value : productPrice" />
    <br />
    <h2> <span id="spnMessagek" data-bind="text:message"></span> </h2>



You can see in View implementation that we are binding Product Name, Product Price and Message to different elements.

Step 2: Creating ViewModel

A ViewModel can be created as a simple JavaScript Objects. We need to keep in mind that to enable Two Way Binding properties of object should be as Knockout Observable. ViewModel can be created as follows,


 var ProductViewModel =
      {
          productName: ko.observable("Pen"),
          productPrice: ko.observable(200),
                 
      };


Next we need to create Message property as Computed Observable. Computed Observable can be created follows,

image

To create computed observable you need to pass a function and name of the ViewModel. Note that there are various ways to create ViewModel. For purpose of this post we followed this approach to add computed observable to ViewModel.

As last step we need to apply binding or link ViewModel to a Node on DOM. If you want to bind ViewModel to whole body then you can skip second parameter.

image

Putting above discussion together and full source code to create app using MVVM and KO are as follows


   var ProductViewModel =
      {
          productName: ko.observable("Pen"),
          productPrice: ko.observable(200),
                 
      };

    ProductViewModel.message= ko.computed(function () {
        var m = this.productName() +
                 " costs " +
                 this.productPrice();
        return m;
    }, ProductViewModel)

    ko.applyBindings(ProductViewModel)


Now let us go ahead and run application.

clip_image001[6]

In above application when you change value in any of the input boxes, immediately message in label will be changed.

So we witnessed that two way binding and automatic UI refresh is very simple to implement using Knockoutjs.  I hope you find this post 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');

&nbsp;

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.

How to setup JavaScript Build in Sublime Text 2

Yes I am turning friend of Sublime Text and thought to use Sublime for JavaScript development as well. To execute JavaScript in Sublime, you need to create new Build System for JavaScript. There are two steps you need to follow,

  1. Install Node.js
  2. Create new build system for JavaScript

To install Node navigate to http://nodejs.org/ and click on download.

clip_image001

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_image002

Once Node is installed you need to create Build System for JavaScript. To do that navigate to

Tools -> Build Systems->New Build System

Here you need to write below code.

clip_image003

After this you can save file with any desired name. I am giving name as JavaScript-Sublime. Once you saved the file go to Tools-> Build System and you should able to see JavaScript-Sublime Build.

clip_image004

You need to select this build. After this go and write a simple JavaScript

clip_image005

And when you press Ctrl+B , you should able to get desired output as follows ,

clip_image006

So happy writing JavaScript in SublimeText. 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.