Search This Blog

Showing posts with label MEAN Stack Tutorials. Show all posts
Showing posts with label MEAN Stack Tutorials. Show all posts

2016-02-17

Important concepts about Javascript for Node JS Developer

Special Values
Null,undefined,{},NaN,Infinity

Special Datatype
object,function,string,number

Typecase
parseInt(),parseFloat(),Boolean()

check datatype :
typeof()-return as string like 'number','object'
instanceof-[] instanceof Array=>true
isNaN(),isFinite()

String Functions:
length,indexOf(),substr(),slice(),split,trim(),search(REGULAR EXPR)

Create Object:
var obj1={first_name='manab',last_name='basu'}

delete properties from object:
delete user.first_name

to add properties in object :
user["first_name"]="Manab"

lenght Of Object
Object.keys(user).length

Array:
Create Array:var arr=[] or var arr=['a','b','c']
typeof arr=Object

Check : Array.isArray(arr)

Add Item: arr.push('a') or arr[4]='a' or arr.unshift('c')- add element at beginning

Delete Item-delete arr[3] or arr.pop()-pop item from the end,arr.shift()-Remove item from begening

Extract Element from array-arr.splice(START_INDEX,NO OF ELEMENT) & it reduce the array size based on NO OF ELEMENT

String to array:"A,b,c".split(',');

Array to string:[1,2,3].join(":");=>1:2:3

Sort:arr.sort()

Sort String of array(names):
names.sort(function(a, b){
var a1=a.toLowerCase(),b1=b.toLowerCase();
    if(a1 < b1) return -1;
    if(a1 > b1) return 1;
    return 0;
})

Functions:
check arguments:write- console.log(arguments);- within function

Constraint
Ternary Operator: var x=today?"X":"Y"

prototype:The prototype property is initially an empty object, and can have members added to it - as you would any other object.
var myObject = function(name){
    this.name = name;
    return this;
};
console.log(typeof myObject.prototype); // object
myObject.prototype.getName = function(){//adding a new member getName() to the class myObject
    return this.name;
};
or
function Shape(){
};
Shape.prototype.X=0;
Shape.prototype.Y=0;
Shape.prototype.move=function(x,y){
 this.X=x;
 this.Y=y;
}
Shape.prototype.distance=function(){
 return Math.sqrt(this.X*this.X+this.Y*this.Y);
}
//call
var s=new Shape();
s.move(10,10);
console.log(s.distance());

Inheritance:
function Square(){}
Square.prototype=new Shape();
Square.prototype.__proto__=Shape().prototype;
Square.prototype.width=0;
Square.prototype.area=function(){
 return this.width*this.width;
}
var sq=new Square();
sq.move(5,5);
sq.width=15;
console.log(sq.distance());
console.log(sq.area());
Error Handling:
function test(){
 throw new Error("Bad Error");
}
//Calling Function
try{
 test();
}
catch(e){
 console.log(e.message);
}
Global: global object
global.name="Manab";
global["name"];

Node Js Cluster

A cluster is a pool of similar workers running under a parent Node process. Workers are spawned using the fork() method of the child_processes module. This means workers can share server handles and use IPC (Inter-process communication) to communicate with the parent Node process.

The master process is in charge of initiating workers and controlling them. You can create an arbitrary number of workers in your master process. Moreover, remember that by default incoming connections are distributed in a round-robin approach among workers (except in Windows).

A cluster module contains several events. Two common events related to the moments of start and termination of workers are the online and the exit events. online is emitted when the worker is forked and sends the online message. exit is emitted when a worker process dies.

Example:

package.json
{
  "name": "democluster",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies":{
    "express":"*"
  }
}


index.js

var cluster = require('cluster');
if(cluster.isMaster) {
    var numWorkers = require('os').cpus().length;
    console.log('Master cluster setting up ' + numWorkers + ' workers...');
    for(var i = 0; i < numWorkers; i++) {
        cluster.fork();
    }
    cluster.on('fork', function(worker) {
        console.log('worker:' + worker.id + " is forked");
    });
    cluster.on('online', function(worker) {
        console.log('worker:' + worker.id + " is online");
    });
    cluster.on('listening', function(worker) {
        console.log('worker:' + worker.id + " is listening");
    });
    cluster.on('disconnect', function(worker) {
        console.log('worker:' + worker.id + " is disconnected");
    });
    cluster.on('exit', function(worker) {
        console.log('worker:' + worker.id + " is dead");
        console.log('Starting a new worker');
        cluster.fork();
    });

  
} else {
    var app = require('express')();
    app.all('/*', function(req, res) {res.send('process ' + process.pid + ' says hello!').end();})
    var server = app.listen(8000, function() {
        console.log('Process ' + process.pid + ' is listening to all incoming requests');
    });
}


OUTPUT IN CONSOLE:

Master cluster setting up 4 workers...
worker:1 is forked
worker:2 is forked
worker:3 is forked
worker:4 is forked
worker:1 is online
worker:4 is online
worker:2 is online
worker:3 is online
Process 8892 is listening to all incoming requests
worker:1 is listening
Process 16192 is listening to all incoming requests
worker:4 is listening
Process 9412 is listening to all incoming requests
Process 15596 is listening to all incoming requests
worker:3 is listening
worker:2 is listening

Reference: http://www.sitepoint.com/how-to-create-a-node-js-cluster-for-speeding-up-your-apps/

2016-02-09

Node js Child Process -exec, spawn and fork

There are two methods for running child processes under Node.js - exec and spawn.

child_process.exec(command, [options], callback)=>exectest.js
child_process.spawn(command, [args], [options])=>spawntest.js
There is an alternative of exec called spawn. Unlike exec it launches a new process and should be used if we expect long-time communication with the running command.

Exec() and spawn() both create processes, but they differ in what they return, spawn returns streams (stdout & stderr), while exec returns a buffer with a max size. Spawn() should be used when the process returns large amount of data.

 Another difference is that spawn() starts receiving the response as soon as the process starts executing, and exec() otherwise waits for the process to end and tries to return all the buffered data at once

 The fork method is a special case of the spawn() functionality, it only creates Node processes. Its signature is the following:

 child_process.fork(modulePath, [args], [options])=>forktest.js

Difference Between Spawn, fork and exec :

 require('child_process').spawn() starts sending back data from the child process in a stream as soon as the child process starts executing. When you run this command, it send a system command that will run on its own process rather than executing code within your node process. In this no new V8 instance will be created and only one copy of the node module will be active on the processor. It is used when you want the child process to return large amount of data to Node.

require('child_process').fork() is a special instance of spawn thats runs a new instance of the V8 engine. Which actually means you are creating multiple workers running on the same Node code base for different task.

require('child_process').exec() returns a buffer from the child process. The default buffer size is 200k. It is asynchronous, but it waits for the child process to end and tries to return all the buffered data at once. If your return data from the child process is greater than 200k then you will get maxBuffer exceeded.

ref:http://www.codingdefined.com/2014/08/difference-between-fork-spawn-and-exec.html

Example :

package.json:

{
  "name": "demochildprocess",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

exectest.js

const
fs = require('fs'),
process = require('child_process');

for(var i=0; i<3; i++) {
 var ls = process.exec('node worker.js '+i, function (error, stdout, stderr) {
    if (error) {
      console.log(error.stack);
      console.log('Error code: '+error.code);
      console.log('Signal received: '+error.signal);
    }
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);

  });

  ls.on('exit', function (code) {
    console.log('Child process exited with exit code '+code);
  });

}

/*Output:
Child process exited with exit code 0
stdout: Process 0 at work
stderr:

Child process exited with exit code 0
stdout: Process 1 at work
stderr:

Child process exited with exit code 0
stdout: Process 2 at work
stderr:*/

spawntest.js

const
 fs = require('fs'),
 process = require('child_process');

/*Create 10 worker process*/
for(var i=0; i<3; i++) {
 var ls = process.spawn('node', ['worker.js', i]);

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

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

 ls.on('close', function (code) {
   console.log('child process exited with code ' + code);
 });
}

/*
stdout: Process 0 at work

stdout: Process 1 at work

child process exited with code 0
child process exited with code 0
stdout: Process 2 at work

child process exited with code 0
*/

forktest.js

const
 fs = require('fs'),
 process = require('child_process');
   

for(var i=0; i <3; i++) {
 var ls = process.fork("worker.js", [i]);

 ls.on('close', function (code) {
   console.log('child process exited with code ' + code);
 });
}

/*
Process 0 at work
child process exited with code 0
Process 1 at work
Process 2 at work
child process exited with code 0
child process exited with code 0

*/


Node Session Management using memcached and run Proxy Server as Windows Service

To Install as a windows service:
npm install winser --save
package.json should contain "start": "node proxy-server.js"
run C:\Manab\Education\nodedemo\demomultiprocessor\node_modules\.bin\winser -i and check services.msc->proxy_demo->and start the service
open three command prompt and type 'node server.js 8081','node server.js 8082',node server.js 8083' respectively in 3 cmd prmpt and call proxy by http://localhost:8080.We can see response from 3 node server for each request.


Uninstall windows service :
C:\Manab\Education\nodedemo\demomultiprocessor\node_modules\.bin\winser -r

Session management in node when running on multiple server:
Downaload memcached in C:\Manab\Education\nodedemo\demomultiprocessor\memcached from https://commaster.net/content/installing-memcached-windows and
run following command to install as a windows local service (as administrator)
C:\Manab\Education\nodedemo\demomultiprocessor\memcached>memcached -d install
run below command to start the service
C:\Manab\Education\nodedemo\demomultiprocessor\memcached>net start memcached

Set memory and port for memcached :
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached=>imagepath="C:\Manab\Education\nodedemo\demomultiprocessor\memcached\memcached.exe" -d runservice -m 10 -p 12345
install memcached modules
npm install memcached --save
and use the imagepart port while creating the object of memcached in server.js
var Memcached = require('memcached');
var memcached = new Memcached('localhost:12345');

Code :

server_list.json :

{
 "servers" :[
 {
  "host":"localhost",
  "port":"8081"
 },
 {
  "host":"localhost",
  "port":"8082"
 },
 {
  "host":"localhost",
  "port":"8083"
 }
           ]
}

Package.json :

{
  "name": "proxy_demo",
  "version": "1.0.0",
  "description": "demo the proxy",
  "main": "index.js",
  "scripts": {
    "start": "node proxy-server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "http-proxy": "0.8.x",
    "memcached": "^2.2.1",
    "winser": "^1.0.2"
  },
  "start": "node proxy-server.js"
}

server.js :

var http=require("http");
var Memcached = require('memcached');
var memcached = new Memcached('localhost:12345');
var lifetime = 86400;
var lastport='';
console.log("Creating server");
var s=http.createServer(function(req,res){
 console.log("listing on "+process.argv[2]);
 memcached.get('lastport', function( err, result ){
  if( err ) console.error( err );
   lastport=result;
   console.dir('reading lastport'+ lastport );
   res.end("I am listing on port:" + process.argv[2] + "and last port is " +lastport);
 
 })
 memcached.set('lastport', process.argv[2], lifetime, function( err, result ){
  if( err ) console.error( err );
  console.dir( result );
 });
 //res.end("I am listing on port:" + process.argv[2]);
});
s.listen(process.argv[2]);

proxy-server.js :

var http_proxy=require("http-proxy");
var fs=require("fs");
var servers=JSON.parse(fs.readFileSync('server_list.json')).servers;
var s=http_proxy.createServer(function(req,res,proxy){
var target=servers.shift();
console.log(target);
proxy.proxyRequest(req,res,target);
servers.push(target);
});
s.listen(8080);

run: node proxy-server.js

Open browser and try http://localhost:8080





2016-01-11

Angular JS Tutorial9: services,factory,provider

AngularJS Service, Factory or Provider all are used for the same purpose of creating utility function that can be used throughout the page with inject-able object. However, the way it is created and the way it is used are different. Here we shall try to understand them clearly.


AngularJS Service:
Angular Service is used to for sharing utility functions with the service reference in the controller. Service is singleton in nature so for once service only one instance is created in the browser and the same reference is used throughout the page.In the service, we create function names as property with this object.

AngularJS Factory :
The purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.

AngularJS Provider:
The purpose of this is again same however Provider gives the output of it's $get function.

Example :

9.html:

<!DOCTYPE html>
<html lang="en">
<head>
 <title>services,factory,provider</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="9controller.js"></script>

</head>
<body ng-app="myapp" ng-controller="mycontroller">
 {{mymessage}}

</body>
</html>

9controller.js:
var app=angular.module('myapp',[]);

app.service('myservice',function(){
 this.mymessage='this is from my service';
}
);
app.factory('myfactory',function(){
 var factory={};
 factory.mymessage='this is from my factory';
 return factory;
}
);
app.provider('myprovider',function(){
 var m1='this is from my provider';
 return {
  setMessage:function(name){//1)its required,if we need set the value
   m1 += name;
  },
  $get:function(){
   return {
    message:m1
   }
  }
 }
});
//2)its required,if we need set the value
app.config(function(myproviderProvider){//ProviderSuffix
 myproviderProvider.setMessage("Manab");
});
app.controller('mycontroller',function($scope,myservice,myfactory,myprovider){
 $scope.mymessage=[myservice.mymessage,myfactory.mymessage,myprovider.message];
});
// app.controller('mycontroller',function($scope,myservice,myfactory){
//  $scope.mymessage='ddd';
// });


Output:


Angular JS Tutorial8: $digest and $watch

$digest() is useful when we want to hook up a vanilla javascript in angularjs.

When you create a data binding from somewhere in your view to a variable on the $scope object, AngularJS creates a "watch" internally. A watch means that AngularJS watches changes in the variable on the $scope object. The framework is "watching" the variable. Watches are created using the $scope.$watch() function


<!DOCTYPE html>
<html lang="en" >
<head>
 <title>$digest,$watch</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

 <script type="text/javascript">
  var application=angular.module('myapp',[]);
  application.controller('mycontroller',function($scope)
  {
   $scope.myRandomNumber=Math.random();
   $scope.counter=-1;
   document.querySelector('input').addEventListener('click',function(){
    $scope.myRandomNumber=Math.random();
    $scope.$digest();
    $scope.$watch('myRandomNumber',function(newValue,oldValue)
    {
     if($scope.counter==5)
      alert('You reach at 5');
     $scope.counter++;
    }
    );
   },false);
  }
  );
 </script>
</head>
<body ng-app="myapp" ng-controller="mycontroller">
 {{myRandomNumber}}
 <br/>
 <input type="button" value="Generate Random Number"/>
</body>
</html>


Angular JS Tutorial7: http service and Search Filter

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.

Example :

Create a sample data file 7data.json as below
{
 "customers":[
  {
  "Name":"Steve",
  "Age":"30",
  "Location":"eastleigh"
  },
  {
   "Name":"Ari",
   "Age":"40",
   "Location":"eastleigh"
  },
  {
   "Name":"Clare",
   "Age":"35",
   "Location":"hedgeend"
  },
  {
   "Name":"Stu",
   "Age":"20",
   "Location":"southampton"
  }
   ]
}

7.html:
<!DOCTYPE html>
<html lang="en" >
<head>
 <title>$http,searchFilter</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="7controller.js"></script>
</head>
<body ng-app="myapp">
 <div ng-controller="mycontroller">
  <ul>
   <h2>Customer Details</h2>
   Any Search:<input type="text" ng-model="searchcriteria.$"></br></br>
   Name Search:<input type="text" ng-model="searchcriteria.Name"></br></br>
   Age Search:<input type="text" ng-model="searchcriteria.Age"></br></br>
   Location Search:<input type="text" ng-model="searchcriteria.Location"></br></br></br>
   <li ng-repeat="customer in customerdata|filter:searchcriteria">
  
     {{"Name:"+customer.Name+" Age:"+customer.Age +" Location:"+customer.Location}},
   
   </li>
  </ul>
 </div>
</body>
</html>

7controller.js :
var app=angular.module('myapp',[]);
app.controller('mycontroller',function($scope,$http){
 $http.get('http://localhost:8080/7data.json')
 .success(function(response)
 {
  $scope.customerdata=response.customers;
 }
 );
}
);

Output :



Angular JS Tutorial6: Login page using routeScope,check,resolve,location

We can control login/authorization using routeScope,check,resolve,location.

Example :

6.html :

<!DOCTYPE html>
<html lang="en">
<head>
 <title>routeScope,check,resolve,location</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="angular-route.js"></script>
 <script src="6controller.js"></script>
</head>
<body  ng-app="myapp">
 <div ng-view></div>
</body>
</html>

6controller.js :

var app=angular.module('myapp',['ngRoute']);
app.config(function($routeProvider){
 $routeProvider
 .when('/',{
  templateUrl:'6login.html',
  //template:'Loaded from /'
 })
 .when('/dashboard',{
  resolve:{
   "check":function($location,$rootScope){
    if(!$rootScope.loggedIn)
    {
     $location.path('/');
    }
   }
  },
  templateUrl:'6dashboard.html'
 })
 .otherwise({
  redirectTo:'/'
 });
});
app.controller('loginCtrl',function($scope,$location,$rootScope){
 $scope.submit=function(){
 

  if($scope.username=='Admin' && $scope.password=='Admin'){
   $rootScope.loggedIn=true;
  
   $location.path('/dashboard');
  }
  else{
   alert('wrong credential');
  }
 };
});

6login.html :

<div ng-controller="loginCtrl">
 <form action="/" id="myloginform">
  User Name : <input type="text" ng-model="username" id="username"/><br/>
  Password : <input type="password" ng-model="password" id="password"/>
  <button type="button" ng-click="submit()">Login</button>
 </form>
</div>

6dashboard.html :

Welcome to Dashboard

Angular JS Tutorial5: ngroute

The ngRoute module provides routing for angular apps.

We can download angular-route.js from the below location
e.g. //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js
where x.y.z indicates the version on angular-route.js like 1.3.5

Example :

5.html:

<!DOCTYPE html>
<html lang="en">
<head>
 <title>ngRoute</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="angular-route.js"></script>
 <script src="5controller.js"></script>
</head>
<body  ng-app="myapp">
 <div ng-view></div>
</body>
</html>

5controller.js :

var app=angular.module('myapp',['ngRoute']);
app.config(function($routeProvider){
 $routeProvider
 .when('/',{
  templateUrl:'5a.html',
  //template:'Loaded from /'
 })
 .when('/fiveb',{
  templateUrl:'5b.html'
 })
 .when('/fivec',{
  templateUrl:'5c.html'
 })
 .otherwise({
  redirectTo:'/'
 });
});

5a.html:
I am in 5a<a href="#/fiveb">Open fiveb</a>

5b.html:
I am in 5b

5c.html:

<a href="#/fiveb">Open fiveb</a>I am in 5c



Angular JS Tutorial4: ng-include

ng-include fetches, compiles and includes an external HTML fragment.

Example:
<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
 <title>ng-includes</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
 <div ng-include="'4a.html'"></div> <!-- Need localhost to test this example -->
</body>
</html>

Angular JS Tutorial3: ng-controller,filter

The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.

MVC components in angular:

•Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties are accessed through bindings.

•View — The template (HTML with data bindings) that is rendered into the View.

•Controller — The ngController directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values.

Filter selects a subset of items from array and returns it as a new array.

Example :

<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head>
 <title>ng-controller,filter</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>
<body>
 <div ng-controller="mycontroller">
  {{mylanguage|uppercase}}
  <button ng-click=changelang()>Change Language to Bengali</button>
 </div>

 <script type="text/javascript">
  var application=angular.module('myapp',[]);//[] : use for referring other module
  application.controller('mycontroller',function($scope)
  {
   $scope.mylanguage='English';
   $scope.changelang=function(){
    $scope.mylanguage='Bengali';
   }
  }
  );
 </script>
</body>
</html>


Output:

Angular JS Tutorial2: ng-init,ng-repeat,sharedscope

The ng-init directive initializes application data.

The ngRepeat directive instantiates a template once per item from a collection.

In order to share data between scopes by model, use the model property like samplemode.sampledata

Example :

<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
 <title>ng-init,ng-repeat,sharedscope</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>
<body>
 <div ng-init="menu='chicken';
 places=[
 {country:'UK',city:'Southampton'},
 {country:'Europe',city:'Paris'},
 {country:'India',city:'Kolkata'},
 ]">
  <input type="text" ng-model="menu"/>
 </div>
<br/>
Share the data between this textbox and textboxes inside the country:city loop use the property like 'message.sharescope'<br/>
Otherwise it will be unidirectional binding from outer ti inner loop, when you use only 'message'<br/>
<input type="text" ng-model="message.sharescope"/><!--to share data between scope, use the property like 'message.sharescope' inplace of 'message', else innser scope value will not be passed to outer scope-->
<p ng-repeat="place in places">
 {{place.country}} :{{place.city}}
 <input type="text" ng-model="message.sharescope">
 <br/>
</p>
</body>
</html>


Output


2016-01-05

Angular JS Tutorial1: ng-model,ng-bind and Expression

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
Typically, we don't use ngBind directly, but instead you use the double curly markup like {{ expression }} which is similar but less verbose.

It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before Angular compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

Example:

Before staring Angular Expression, create the web server using node.js with the below file

1)Package.json:

{
  "name": "angulardetails",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies" : {
    "connect"         : "*",
    "serve-static"    : "*"
 
  }
}

2)index.js

var connect=require("connect");
var serveStatic=require("serve-static");

var app=connect()
.use(serveStatic('public'))
.use(function  (req,res) {
res.end("Welcome to the Static Demo");
})
.listen(8080);

console.log("listening from port 8080");

3)Create a public folder in the root.

4)run npm install to install dependencies

5)run using 'node index.js'

Now create angular.js file "1.html" with in the public folder


<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
<title>ng-model,ng-bind,Expression</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>
<body>
Info: ng-model works on input, ng-bind on div<br/>
<input type="text" ng-model="name"/>
<div >Hello {{name}}</div>

Hello <div ng-bind="name"></div>
<div data-ng-bind="name"></div>
<div ng:bind="name"></div>
<div ng_bind="name"></div>
<div >Expression {{10*12}}</div>
</body>
</html>


See your angular js file in browser by typing the URL "http://localhost:8080/1.html"




2015-12-21

Node JS debugging

Node Inspector is a debugger interface for Node.js applications.

Install the Node Inspector by the following command.
$ npm install -g node-inspector

Debug your application by the following command.The node-debug command will load Node Inspector in your default browser.
node-debug index.js

Use the debugger; in your code , to watch the values/debug , when you call node js app from HTML based client App.

2015-12-19

Install NodeJS without Admin Right

1)Download nodejs from below location and extract to some local folder
http://nodejs.org/dist/latest/

2)Download npm from the below location and extract to some local folder
https://github.com/npm/npm/releases

3)Set PATH Variable either by below command or from Environment variable setting in your computer, when you have access
set PATH=%PATH%;C:\NODE_LOC\;C:\NPM_LOC


4)Set up NPM when its behind proxy
npm config set proxy http://proxy:port
npm config set https-proxy https://proxy:port
or with credential
npm config set proxy http://username:password@proxy:port
npm config set https-proxy https://username:password@proxy:port


5)Test by the below command
>node -v
>npm -v
--------------------------------------------------------------------------------------------------------------
Check the current setting by following comment :
npm config ls -l

Remove the Proxy set as above step 4 :
npm config rm proxy npm config rm https-proxy

Some strange issues can be resolved by the following commands :
npm cache clean

2015-12-17

Mongodb Overview

Installation :

Download Mongodb from below location

https://www.mongodb.org/downloads#production

Custom installation, in order to set a simple installation location like C:\Manab\MongoDB

Set the Environment Variable(PATH) as below

C:\Manab\MongoDB\Server\3.0\bin

Run :

mongod.exe --dbpath C:\Manab\MongoDB\data

Open another command prompt and navigate to the below location

C:\>cd C:\Manab\MongoDB\Server\3.0\bin

and type mongo.exe

Useful commands :

>show dbs : To check all the dbs exist in your mongodb server

>db.hostInfo() : To get the host information

>db.stats() :-To get stats about mongodb server type

>use fastcuredb :-To create database,It will not display in 'show dbs' list, until have any document

>db :-To check your currently selected database

>db.delete.insert({"name":"Manab Sample DB"}) / db.delete.insert({"name":"Arpana Basu","location":"UK"})

>show collections :-To see all the collections in the db

>db.createCollection("delete2") :-To create a new collection

>db.createCollection("delete3", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } ) :-Create collection with parameter, can be seen by 'db.delete3.stats()'

>db.COLLECTION_NAME.find() /db.COLLECTION_NAME.find().pretty():-To query data either non formatted or formatted way(pretty), i.e db.delete.find()

>db.delete.find({"name":"Arpana Basu"}) /db.delete.find({"name":/Arpana/})/ db.delete.find({"name":/.*Arpana.*/,"location":"UK"}) /db.delete.find().limit(1)/db.delete.find().limit(1).skip(1)/db.delete.find().limit(1).sort({"name":-1})

>db.delete.update({"name":"Arpana Basu"},{$set:{"name":"Arpana B","location":"England"}})

>db.delete.remove({"name":"Arpana B"}) /db.delete.remove({"name":"Arpana B"},1)/ db.delete.remove()

>db.delete.ensureIndex({"name":1,"location":-1})
-db.delete.update({"name":"Arpana Basu"},{$set:{"age":30}})
-db.delete.update({"name":"Manab Sample DB"},{$set:{"location":"UK","age":34}})

>db.delete.aggregate([{$group : {_id : "$location", people : {$sum : 1}}}])--Sum of people group by Country
db.delete.aggregate([{$group : {_id : "$location", people : {$avg : 1}}}])--avg of people group by Country

>db.COLLECTION_NAME.drop() :- To delete collection i.e db.delete3.drop()

>db.dropDatabase :-to drop a existing database

>db.help()

Additional DB level commands :

        db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]
        db.auth(username, password)
        db.cloneDatabase(fromhost)
        db.commandHelp(name) returns the help for the command
        db.copyDatabase(fromdb, todb, fromhost)
        db.createCollection(name, { size : ..., capped : ..., max : ... } )
        db.createUser(userDocument)
        db.currentOp() displays currently executing operations in the db
        db.dropDatabase()
        db.eval() - deprecated
        db.fsyncLock() flush data to disk and lock server for backups
        db.fsyncUnlock() unlocks server following a db.fsyncLock()
        db.getCollection(cname) same as db['cname'] or db.cname
        db.getCollectionInfos()
        db.getCollectionNames()
        db.getLastError() - just returns the err msg string
        db.getLastErrorObj() - return full status object
        db.getLogComponents()
        db.getMongo() get the server connection object
        db.getMongo().setSlaveOk() allow queries on a replication slave server
        db.getName()
        db.getPrevError()
        db.getProfilingLevel() - deprecated
        db.getProfilingStatus() - returns if profiling is on and slow threshold
        db.getReplicationInfo()
        db.getSiblingDB(name) get the db at the same server as this one
        db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
        db.hostInfo() get details about the server's host
        db.isMaster() check replica primary status
        db.killOp(opid) kills the current operation in the db
        db.listCommands() lists all the db commands
        db.loadServerScripts() loads all the scripts in db.system.js
        db.logout()
        db.printCollectionStats()
        db.printReplicationInfo()
        db.printShardingStatus()
        db.printSlaveReplicationInfo()
        db.dropUser(username)
        db.repairDatabase()
        db.resetError()
        db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
        db.serverStatus()
        db.setLogLevel(level,)
        db.setProfilingLevel(level,) 0=off 1=slow 2=all
        db.setWriteConcern( ) - sets the write concern for writes to the db
        db.unsetWriteConcern( ) - unsets the write concern for writes to the db
        db.setVerboseShell(flag) display extra information in shell output
        db.shutdownServer()
        db.stats()
        db.version() current version of the server

Additional Collection Level Commands :

        db.test.find().help() - show DBCursor help
        db.test.count()
        db.test.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
        db.test.convertToCapped(maxBytes) - calls {convertToCapped:'test', size:maxBytes}} command
        db.test.dataSize()
        db.test.distinct( key ) - e.g. db.test.distinct( 'x' )
        db.test.drop() drop the collection
        db.test.dropIndex(index) - e.g. db.test.dropIndex( "indexName" ) or db.test.dropIndex( { "indexKey" : 1 } )
        db.test.dropIndexes()
        db.test.ensureIndex(keypattern[,options])
        db.test.explain().help() - show explain help
        db.test.reIndex()
        db.test.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                      e.g. db.test.find( {x:77} , {name:1, x:1} )
        db.test.find(...).count()
        db.test.find(...).limit(n)
        db.test.find(...).skip(n)
        db.test.find(...).sort(...)
        db.test.findOne([query])
        db.test.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
        db.test.getDB() get DB object associated with collection
        db.test.getPlanCache() get query plan cache associated with collection
        db.test.getIndexes()
        db.test.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
        db.test.insert(obj)
        db.test.mapReduce( mapFunction , reduceFunction , )
        db.test.aggregate( [pipeline], ) - performs an aggregation on a collection; returns a cursor
        db.test.remove(query)
        db.test.renameCollection( newName , ) renames the collection.
        db.test.runCommand( name , ) runs a db command with the given name where the first param is the collection name
        db.test.save(obj)
        db.test.stats({scale: N, indexDetails: true/false, indexDetailsKey: , indexDetailsName: })
        db.test.storageSize() - includes free space allocated to this collection
        db.test.totalIndexSize() - size in bytes of all the indexes
        db.test.totalSize() - storage allocated for all data and indexes
        db.test.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi
        db.test.validate( ) - SLOW
        db.test.getShardVersion() - only for use with sharding
        db.test.getShardDistribution() - prints statistics about data distribution in the cluster
        db.test.getSplitKeysForChunks( ) - calculates split points over all chunks and returns splitter function
        db.test.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
        db.test.setWriteConcern( ) - sets the write concern for writes to the collection
        db.test.unsetWriteConcern( ) - unsets the write concern for writes to the collection

Mongodb Datatype :
MongoDB supports many datatypes whose list is given below:

String : This is most commonly used datatype to store the data. String in mongodb must be UTF-8 valid.
Integer : This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
Boolean : This type is used to store a boolean (true/ false) value.
Double : This type is used to store floating point values.
Min/ Max keys : This type is used to compare a value against the lowest and highest BSON elements.
Arrays : This type is used to store arrays or list or multiple values into one key.
Timestamp : ctimestamp. This can be handy for recording when a document has been modified or added.
Object : This datatype is used for embedded documents.
Null : This type is used to store a Null value.
Symbol : This datatype is used identically to a string however, it's generally reserved for languages that use a specific symbol type.
Date  : This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.
Object ID : This datatype is used to store the document’s ID.
Binary data : This datatype is used to store binay data.
Code : This datatype is used to store javascript code into document.
Regular expression : This datatype is used to store regular expression

2015-12-05

Node JS Streams

A stream is an abstract interface implemented by various objects in Node.js. For example a request to an HTTP server is a stream. Streams are readable, writable, or both. All streams are instances of EventEmitter

You can load the Stream base classes by doing require('stream'). There are base classes provided for Readable streams, Writable streams, Duplex streams(both readable and writable), and Transform streams(Transform streams are Duplex streams where the output is in some way computed from the input).

Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are:
  • data - This event is fired when there is data is available to read.
  • end - This event is fired when there is no more data to read.
  • error - This event is fired when there is any error receiving or writing data.
  • finish - This event is fired when all data has been flushed to underlying system
Example:

Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.

Step 3: index.js will be as below

var fs = require("fs");
var data = '';


// Create a readable stream
var readerStream = fs.createReadStream('myinputfile.txt');

// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {//The data event is fired when there is data is available to read.
   console.log('data event from Read Stream');
   data += chunk;
});

readerStream.on('end',function(){//The end event is fired when there is no more data to read.

   console.log('end event from Read Stream: ' + data);
});

readerStream.on('finish',function(){//The finish event is fired when all data has been flushed to underlying system
   console.log('finish event from Read Stream: ' +data);
});

readerStream.on('error', function(err){//The Error event is fired when there is any error receiving or writing data.
   console.log(err.stack);
});

console.log("Program Ended for Read Stream");
///////---------------------------------Write Stream--------------------------------------
console.log(data);
data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed from write Stream.");
});

writerStream.on('error', function(err){
   console.log(err.stack);
});

console.log("Program Ended for write stream");

Step 4: Create a new file 'myinputfile.txt' within the root folder with the text  'Hi, This is Manab'

Step 5:Run the application by 'node index.js'

Step 6: You could see a new file 'output.txt' has been generated within the root and below is the output in command prompt

Node JS File System

Node File System (fs) module can be imported using following syntax:
var fs = require("fs")
Every method in fs module have synchronous as well as asynchronous form. Asynchronous methods takes a last parameter
as completion function callback and first parameter of the callback function is error. It is preferred to use
asynchronous method instead of synchronous method as former never block the program execution where as the second one
does.
-----------------------------------------------------
fs.open(path, flags[, mode], callback):To open a file in asynchronous mode
var fs = require("fs");
// Asynchronous - Opening File
console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
  console.log("File opened successfully!");    
});
Modes-3 main modes(r-read,w-write,a-append.when suffix is s, it indicates synchonousmode,when + ,it indicates both
operation)
-----------------------------------------------------
fs.read(fd, buffer, offset, length, position, callback):To read the file
var fs = require("fs");
var buf = new Buffer(1024);
console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Going to read the file");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + " bytes read");
     
      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});
-----------------------------------------------------
fs.writeFile(filename, data[, options], callback):This method will over-write the file if file already exists.
var fs = require("fs");
console.log("Going to write into existing file");
fs.writeFile('input.txt', 'Simply Easy Learning!',  function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("Data written successfully!");
   console.log("Let's read newly written data");
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Asynchronous read: " + data.toString());
   });
});
-----------------------------------------------------
fs.close(fd, callback):To close an opened file
var fs = require("fs");
var buf = new Buffer(1024);
console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Going to read the file");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
      // Close the opened file.
      fs.close(fd, function(err){
         if (err){
            console.log(err);
         }
         console.log("File closed successfully.");
      });
   });
});

------------------------------------------------------
fs.stat(path, callback):To get the information about a file
var fs = require("fs");
console.log("Going to get file info!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
       return console.error(err);
   }
   console.log(stats);
   console.log("Got file info successfully!");
  
   // Check file type
   console.log("isFile ? " + stats.isFile());
   console.log("isDirectory ? " + stats.isDirectory());   
});
-------------------------------------------------------
fs.unlink(path, callback): To delete a file
var fs = require("fs");
console.log("Going to delete an existing file");
fs.unlink('input.txt', function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("File deleted successfully!");
});
-------------------------------------------------------
fs.ftruncate(fd, len, callback) : To truncate an opened file
var fs = require("fs");
var buf = new Buffer(1024);
console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Going to truncate the file after 10 bytes");
  
   // Truncate the opened file.
   fs.ftruncate(fd, 10, function(err){
      if (err){
         console.log(err);
      }
      console.log("File truncated successfully.");
      console.log("Going to read the same file");
      fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
         if (err){
            console.log(err);
         }
         // Print only read bytes to avoid junk.
         if(bytes > 0){
            console.log(buf.slice(0, bytes).toString());
         }
         // Close the opened file.
         fs.close(fd, function(err){
            if (err){
               console.log(err);
            }
            console.log("File closed successfully.");
         });
      });
   });
});
-------------------------------------------------------
fs.mkdir(path[, mode], callback): To create a directory
var fs = require("fs");
console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err){
   if (err) {
       return console.error(err);
   }
   console.log("Directory created successfully!");
});
-------------------------------------------------------
fs.rmdir(path, callback) : To remove a directory
var fs = require("fs");
console.log("Going to delete directory /tmp/test");
fs.rmdir("/tmp/test",function(err){
   if (err) {
       return console.error(err);
   }
   console.log("Going to read directory /tmp");
   fs.readdir("/tmp/",function(err, files){
      if (err) {
          return console.error(err);
      }
      files.forEach( function (file){
          console.log( file );
      });
   });
});
-------------------------------------------------------
fs.readdir(path, callback) : To read a directory
var fs = require("fs");
console.log("Going to read directory /tmp");
fs.readdir("/tmp/",function(err, files){
   if (err) {
       return console.error(err);
   }
   files.forEach( function (file){
       console.log( file );
   });
});

Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It allows to set up middlewares to respond to HTTP  Requests and defines a routing table which is used to perform different action based on HTTP Method and URL.It allows to dynamically render HTML Pages based on passing arguments to templates.


To Install Mean Stack run the following comment
  • npm install -g mean-cli
and make the initial structure of the project by following command
  • mean init yourNewApp
or, Run below command to install only the Express
  • npm install express --save                 
There are following important modules which you should install along with express:
  • body-parser - This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser - Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • multer - This is a node.js middleware for handling multipart/form-data.


  • $ npm install body-parser --save
  • $ npm install cookie-parser --save
  • $ npm install multer --save


Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.

Step 3:Amend the package.json as below

{
  "name": "demoforexpress",
  "version": "1.0.0",
  "description": "Demo for Express",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "MRB",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.14.1",
    "cookie-parser": "^1.4.0",
    "express": "^4.13.3",
    "multer": "^1.1.0"
  }
}

Step 4: index.js will be as below

var express = require('express');
var app = express();
app.get('/', function (req, res) {
 console.log("Get method Called")
   res.send('Response from GET method');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
   console.log("Post method called");
   res.send('Response from POST method');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
   console.log("delete method called for /del_user");
   res.send('Response from Delete Method');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
   console.log("get Method called for /list_user");
   res.send('response from GET for /list_user');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {  
   console.log("Got a GET request for /ab*cd");
   res.send('Response from Page Pattern Match');
})
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)
})




Step 5: Run the application by 'node index.js' , test in rest client and see the responses in console.

----------------------------More on Express-------------------------------------
package.json

{
  "name": "demoforexpress",
  "version": "1.0.0",
  "description": "Demo for Express",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "MRB",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.14.1",
    "cookie-parser": "^1.4.0",
    "express": "^4.13.3",
    "multer": "^1.1.0",
    "express-session":"*",
    "connect-busboy":"*",
    "path":"*",
    "fs-extra":"*",
    "formidable":"*"
  }
}

index.js

// fsutil file createnew index.js 2000
var express = require('express');
var app = express();
///-------------Basic Authentication-----------------------
var loginuser;
// Authenticator
app.use(function(req, res, next) {
    var auth;
   
    // check whether an autorization header was send   
    if (req.headers.authorization) {
      // only accepting basic auth, so:
      // * cut the starting "Basic " from the header
      // * decode the base64 encoded username:password
      // * split the string at the colon
      // -> should result in an array
      auth = new Buffer(req.headers.authorization.substring(6), 'base64').toString().split(':');
  
    }
    // checks if:
    // * auth array exists
    // * first value matches the expected user
    // * second value the expected password
    if ((!auth || auth[0] !== 'testuser' || auth[1] !== 'testpassword') && (!auth || auth[0] !== 'testuser2' || auth[1] !== 'testpassword2'))
    {
        // any of the tests failed
        // send an Basic Auth request (HTTP Code: 401 Unauthorized)
        res.statusCode = 401;
        // MyRealmName can be changed to anything, will be prompted to the user
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        // this will displayed in the browser when authorization is cancelled
        res.end('Unauthorized');
    } else {
        // continue with processing, user was authenticated
        loginuser=auth[0];
        next();
    }
    // if (!auth || auth[0] !== 'testuser' || auth[1] !== 'testpassword')
    // {
    //     // any of the tests failed
    //     // send an Basic Auth request (HTTP Code: 401 Unauthorized)
    //     res.statusCode = 401;
    //     // MyRealmName can be changed to anything, will be prompted to the user
    //     res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
    //     // this will displayed in the browser when authorization is cancelled
    //     res.end('Unauthorized');
    // } else {
    //     // continue with processing, user was authenticated
    //     loginuser=auth[0];
    //     next();
    // }
});

////------------------------------End Authentication-------------------------------
app.get('/', function (req, res) {
 console.log("Get method Called")
   res.send('Response from GET method');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
   console.log("Post method called");
   res.send('Response from POST method');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
   console.log("delete method called for /del_user");
   res.send('Response from Delete Method');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
   console.log("get Method called for /list_user");
   res.send('response from GET for /list_user');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {  
   console.log("Got a GET request for /ab*cd");
   res.send('Response from Page Pattern Match');
})
//------------------Cookie---------------------------
//This responds a GET request for cookie
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/cookie', function (req, res) {
  //res.clearCookie("mycookie");
  res.cookie("mycookie","manab",{maxAge:864000000});
  res.setHeader('Content-Type', 'text/plain');
  res.send('Response from GET Cookie method ' +JSON.stringify(req.cookies));
})
//------------------Session---------------------------
//This responds a GET request for session
var session = require('express-session');
app.use(cookieParser());
app.use(session({ secret: 'loginuser', cookie: { maxAge: 60000 }}));
app.get('/session', function (req, res) {
var sess = req.session;
if (sess.views) {
    sess.views++
    res.setHeader('Content-Type', 'text/html')
    res.write('views: ' + sess.views + '
')
    res.write('expires in: ' + (sess.cookie.maxAge / 1000) + 's
')
    res.end()
  } else {
    sess.views = 1
    res.end('welcome to the session demo. refresh!')
  }
})
//------------------Uploading File---------------------------
//HTML For Uploading File
/*<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
    <meta charset="UTF-8">
    <title>angular file upload</title>
</head>
<body>
        <form method='post' action='upload' enctype="multipart/form-data">
        <input type='file' name='fileUploaded'>
        <input type='submit'>
 </body>
</html>*/


var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path');     //used for file path
var fs = require('fs-extra');       //File System - for file manipulation
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
//------------Without formidable--------
// app.route('/upload')
//     .post(function (req, res, next) {
//         var fstream;
//         req.pipe(req.busboy);
//         req.busboy.on('file', function (fieldname, file, filename) {
//             console.log("Uploading: " + filename);
//             //Path where image will be uploaded
//             fstream = fs.createWriteStream(__dirname + '/img/' + filename);
//             file.pipe(fstream);
//             fstream.on('close', function () {   
//                 console.log("Upload Finished of " + filename);             
//                 res.redirect('back');           //where to go next
//             });
//         });
//     });
//--------------------------------------
//------------------Uploading File With formidable
var bodyParser=require("body-parser");
var formidable = require("formidable");
app.use(bodyParser({defer: true}));
 app.route('/upload')
 .post(function (req, res, next) {
  var form = new formidable.IncomingForm();
    //Formidable uploads to operating systems tmp dir by default
    form.uploadDir = "./img";       //set upload directory
    form.keepExtensions = true;     //keep file extension
    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        console.log("form.bytesReceived");
        //TESTING
        console.log("file size: "+JSON.stringify(files.fileUploaded.size));
        console.log("file path: "+JSON.stringify(files.fileUploaded.path));
        console.log("file name: "+JSON.stringify(files.fileUploaded.name));
        console.log("file type: "+JSON.stringify(files.fileUploaded.type));
        console.log("astModifiedDate: "+JSON.stringify(files.fileUploaded.lastModifiedDate));
        //Formidable changes the name of the uploaded file
        //Rename the file to its original name
        fs.rename(files.fileUploaded.path, './img/'+files.fileUploaded.name, function(err) {
        if (err)
            throw err;
          console.log('renamed complete'); 
        });
          res.end();
    });
});

//----------------------------------------------------
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%d:%d", host, port)
})

Create server using HTTP,Express and HAPI

HTTP:
var http=require('http');
var handlerMethod=function(req,res){
 res.end("Hello, This is a message from the handler of web server of");
}
http.createServer(handlerMethod).listen(1234,'localhost');
console.log("Http Server is running");

Express:
var express = require('express');
var app = express();
app.get(*,function(req,res){
 res.end("response from server");
});
var server = app.listen(3000, function(){
    console.log('Listening on port %d', server.address().port);
});

Hapi:
var Hapi = require('hapi');
var server = new Hapi.Server(3000);//port number during initialize
server.start(function () {
    console.log('Server running at:', server.info.uri);
});

Difference between req.params,req.query and req.body :

(req.params) Checks route params, ex: /user/:id
(req.query) Checks query string params, ex: ?id=12 Checks urlencoded body params
(req.body), ex: id=12 To utilize urlencoded request bodies, req.body should be an object. This can be done by using the _express.bodyParser middleware.

Use Basic Authentication in the above example from Adv Rest Client:
URL-http://localhost:8081/
Header would be -Authorization: Basic dGVzdHVzZXI6dGVzdHBhc3N3b3Jk
To change the Authorization,Click on Form ->'Edit Value' for authorization header->Basic

Difference between res.end and res.send :
res.send('Response from POST method');-automatically assumes a Content-Type of html
res.end('Response from POST method');-so no assumptions are made for the Content-Type

Send cookie in response in the above example
use- cookie-parser to set and get cookie in request and response
call -http://localhost:8081/cookie to check also the request cookie which is firsttime set by response cookie


Output - Response from GET Cookie method {"_ga":"GA1.1.2097241217.1451846328","mycookie":"manab"}

Use Session Variable in the above example:
call http://localhost:8081/session from different type of browser , IE+Chrome
Delete Moudles which is can't be deleted for alonger file path name
npm install rimraf -g
rimraf node_modules

Upload file:
ref:http://stackoverflow.com/questions/23691194/node-express-file-upload
node index.js and open http://localhost:8081/index.html
Two example , first one is commented and without formidable , second one with formidable package

2015-11-16

Node.js - Event Loop and Event Emitter

Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur.

Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events.

EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

Below is an example :

Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.
Step 3: index.js will be as below

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
// Create an event handler as follows
var connectHandler = function connected() {
   console.log('connection succesful.');
 
   // Fire the data_received event
   eventEmitter.emit('data_received');
}
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);

// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
   console.log('data received succesfully.');
});
// Fire the connection event
var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'data_received');
console.log(eventListeners + " Listner(s) listening to data_received event");
console.log("Listner Count Ended...............");
eventEmitter.emit('connection');
console.log("Connection Event Ended...............");
eventEmitter.emit('data_received');
console.log("data_received Event Ended...............");
eventEmitter.removeAllListeners();
eventEmitter.emit('connection');
console.log("Program Ended...............");
Step 5: Run the application by 'node index.js' and see the responses in console.