Search This Blog

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

*/


Blog Summary

Feed Of this blog:
http://portal-management.blogspot.com/feeds/posts/default
http://feeds.feedburner.com/PortalAndContentManagement

Translate ToChinese Korean French German Italian
I am Manab from kolkata. Engineering graduate and presently working in an IT company. Love to share my knowledge with all and to make lots of friends.
Adobe Flex
Self Closing Alert in Flex
Validating Email Address in Flex
Validating Integers and Real number in Flex
Validating Numbers in Flex
Drag Drop Treeview nodes in Flex
Toggling Columns of Grid in Flex
File Downloader Control in Flex
Calculate date difference between two selected days
sorting XMLListCollection using MXML Flex
Sort Array Collection in Adobe Flex
.NET and Flex Integration
Flex Tutorials 1-Create a new project and Debug the Flex Application
Flex Tutorials 2-Define absolute layout,VBox & HBox
Flex Tutorials 3-Data binding in Adobe Flex
Flex Tutorials 4-Event Handling in Adobe Flex
Flex Tutorials 5-Navigation Control in Adobe Flex
Flex Tutorials 6-Retrieving XML Data using HTTP Service
Flex Tutorials 7-Handling different viewstate in Adobe Flex
Flex Tutorials 8-Using Datagrid and TileList in Adobe Flex
Flex Tutorials 9-Manipulating XML in Adobe Flex
Flex Tutorials 10-Filter Function in Adobe Flex
Flex Tutorials 11-Sort Function and ICursur in Adobe Flex
Flex Tutorials 12-Valiation Control in Adobe Flex
Flex Tutorials 13-Regular Expression in Adobe Flex
Flex Tutorials 14-Currency Formatter in Adobe Flex
Flex Tutorials 15-How to Call WebService in Adobe Flex
Flex Tutorials 16-Multiple file uploader in .NET using Adobe Flex Swf
Flex Tutorials 17-Animation and Embedding Images in Adobe Flex
Application Architecture
Microsoft Best Practices Analyzer for Windows SharePoint Services 3.0 and the 2007 Microsoft Office System
Design patterns
Application Architecture
Tutorial 1-UML Diagram:Use case
Tutorial 2-UML Diagram:Class diagrams
Tutorial 3-UML Diagram:object diagrams
Tutorial 4-UML Diagram:Sequence diagrams
Tutorial 5-UML Diagram:Collaboration diagrams
Tutorial 6-UML Diagram:Statechart diagrams
Tutorial 7-UML Diagram:Activity diagrams
Tutorial 8-UML Diagram:Component and deployment diagrams
Static Constructor
Implementation of factory Pattern
Implementation of Singleton Pattern
Implementation of Builder Pattern
Design Patterns Overview
C#
Tutorial 1:Getting Started with C#
Tutorial 2:Operators, Types, and Variables
Tutorial 3:Control Statements - Selection
Tutorial 4:Methods
Tutorial 5:Namespaces
Tutorial 6:Introduction to Classes
Tutorial 7:Class Inheritance
Tutorial 8:Polymorphism
Tutorial 9:Properties
Tutorial 10:Indexers
Tutorial 11:Interfaces
Tutorial 12:Delegates
Tutorial 13:Events
Tutorial 14:Exception Handling
ASP.NET
Handling Dropdownlist Event within a Gridview
Some common general important method for .NET
Server side Message box when Ajax is using
ASP.NET Treeview checkbox with select all
ASP Treview Checkbox Work as Radiobutton
Generating PDF from .NET
Generate Excel from Gridview when using Masterpage
HL7 Parsing using .NET
Accessing Server side values from client Side
Upload any file into a database
Progressbar in Ajax
Server side messagebox
How can I enable right click on a control in a aspx webpage
Client Side Callbacks in ASP.NET 2.0
Javascript YES NO Confirm Dialog
.NET and Flex Integration
Gridview With Fixed Header
How to know the IP Address of the user who visit my Site
Call Master page event in Content page
Web Editor for ASP.NET
What is new in .NET 2.0
Check file type of FileUpload control for asp.net
GridView with Fixed Header and Freeze Column
Difference between Constant And Readonly
Difference between ref and out
Disable cache for Popup window in asp.net
Display Image in gridview and export it
Binding ASP .NET Treeview with LINQ to Stored Procedure
Introduction to Entity Framework-Part I
Introduction to Entity Framework-Part II
ASP.NET Tips and Tracks
.NET Tips & Tracks
How to place both VB and CS File in App_Code directory
Delete all files from a folder
EBooks on .NET
Microsoft Best Practices Analyzer for Windows SharePoint Services 3.0 and the 2007 Microsoft Office System
Design patterns
Application Architecture
Free EBooks On .NET
EBooks on Javascript
EBooks on Javascript
EBooks on SQL Server
EBooks on SQL Server
Javascript
Server side Message box when Ajax is using
ASP.NET Treeview checkbox with select all
ASP Treview Checkbox Work as Radiobutton
Accessing Server side values from client Side
Disable Back Button in the browser
Javascript YES NO Confirm Dialog
Parsing Querystring using Javascript
SQL Server
SQL Server
How to empty all the tables in a database
Searching Any String From A Database
Find missing and duplicate number from a sequence of numbers in SQL table
Generate random numbers in T-sql
Sql Server 2005 Mirroring within Workgroup or Domain without FQDN
Dynamic Bulk Copy using OPENXML
Get all Child IDs from Self Referential Table(DFS)
Rank Function in SQL Server
Summarizing Data Using ROLLUP and CUBE
Maximum Capacity of different properties for SQL Server
What are the default databases of SQL Server
How to get records in random order from a sql query in sql server?
Different Isolation Level in SQL Server 2005
SQL Server 2008
What is new in SQL Server 2008
Visual Studio 2008
Anonymous Types
USING LAMBARD EXPRESSION
Tutorials on LINQ
Video Tutorials on .NET 3.5
What is new in .NET 3.5
VS.Net 2008 Tutorial and Training
Tutorial 1:Create a Simple Workflow
Tutorial 2:Receiving Data into the Workflow using Parameters
C# 3.0 Tutorial -1:Var Keyword
C# 3.0 Tutorial -2:Extension Methods
C# 3.0 Tutorial -3:Lambda Expressions
C# 3.0 Tutorial -4:Object Initializers
C# 3.0 Tutorial -5:Anonymous Types
C# 3.0 Tutorial -6:Type Equivalence
C# 3.0 Tutorial -7:Projections
C# 3.0 Tutorial -8:Linq
C# 3.0 Tutorial -9:Linq To Entities
Silverlight with LINQ and WCF
Introduction to Linq To Stored Procedure
WWF
Tutorial 1:Create a Simple Workflow
Tutorial 2:Receiving Data into the Workflow using Parameters
Basics Of Windows Workflow Foundation
WCF
Advantages of WCF over Webservice
Create A Step by Step WCF Application
Basics Of Windows Communication Foundation
Create Multi Layer Architecture using WCF
Visual Studio 2010
Video Tutorials on VS 2010
New Features in .NET Framework 4.0
What is F#
F# As a Language and F# for Developers
Introducing Windows Azure
Sharepoint
Microsoft Best Practices Analyzer for Windows SharePoint Services 3.0 and the 2007 Microsoft Office System
Free Download Sharepoint Template
Step by Step Tutorials for Sharepoint
Introduction to Sharepoint.
How to Get Latest News on Sharepoint Technology
How to create workflow in sharepoint designer
WSS Events
Features in Sharepoint
WSS Content Type
WSS Site Column
Webparts in WSS
Creating WSS Wikies & Blogs
Difference between Windows SharePoint Services (WSS) and Microsoft Office SharePoint Server 2007 (MOSS)
Sharepoint Object Model Overview
SPSite and SPContext
SPSiteDataQuery
SPQuery
SPDocumentLibrary
SPFolder And SPFile
SPContentType
SPField
SPListItem
SPList
SPWeb
How to discover all the list from a site collection
Creating Feature In Sharepoint
Adding an Event Handler to a Feature
Debugging WSS Components
Custom Application Page for the ECB Menu
Creating Custom Application Page
Create Pages Using Object Model
Creating a Simple Webpart using usercontrol
Create SPList programmatically
Create A Simple Feature
Create a simple webpart
Create a connected web part and activate through feature
Create a custom application page in sharepoint 2007
Create Custom Sitepages in Sharepoint 2007
Create a custom Field in Sharepoint 2007
Create a List event receiver feature
XSLT Tutorials
XSLT Tutorials
Miscellaneous
Introduction to Microsoft .NET Micro Framework (NETMF)
Bind MSChart with Dataset and handle Click event of the chart
Cost Estimation
Estimation using Fuction Point Analysis-EI(Part 1)
Estimation using Fuction Point Analysis-EO,EQ(Part 2)
Estimation using Fuction Point Analysis-EIF,ILF(Part 3)
Estimation using Fuction Point Analysis-GSC(Part 4)
Estimation using Fuction Point Analysis-Productivity Factor(Part 5)
Estimation using Fuction Point Analysis-Phase Considaration and cost calculation(Part 6)
Cost Estimation using use case points
Mean Stack
NODE JS and MEAN Stack
Managing Node Version and Editor
Node JS Modules
Creating an HTTP Server using Node JS
Managing HTTP request using Node JS
Configure responses from a Node.js web server
Creating a Node.js HTTP Client Application
Serving a HTML file from Node JS
AngularJS
Angular JS Routing
Node.js - Event Loop and Event Emitter
Express
Node JS File System
Node JS Streams 
Mongodb Overview
Install NodeJS without Admin Right
Node JS debugging
Angular JS Tutorial1: ng-model,ng-bind and Expression...
Angular JS Tutorial2: ng-init,ng-repeat,sharedscope...
Angular JS Tutorial3: ng-controller,filter
Angular JS Tutorial4: ng-include
Angular JS Tutorial5: ngroute
Angular JS Tutorial6: Login page using routeScope,check,resolve,location...
Angular JS Tutorial7: http service and Search Filter...
Angular JS Tutorial8: $digest and $watch
Angular JS Tutorial9: services,factory,provider
Node Session Management using memcached and run node in multiple server using http-Proxy...
Node js Child Process -exec, spawn and fork
Node Js Cluster
Important concepts about Javascript for Node JS De...

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