Wednesday, October 28, 2015

Lets get funny with Node.js

node.js allows you to build scalable network applications using JavaScript on the server side
Its single threaded server

Setup & basic example:

Download node.js code
Compile with prefix path
make and make install
set environment path for node in profile information
go to node install dir, it has 'node' and 'npm' binaries
    npm is for packaging or resolving package dependencies

Basic example:
any server can be run as
$> node app.js
[ e.g. app.js ->
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello node.js\n');
}).listen(8124,"127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
]

if you want to create new app package , one example at below link
https://stormpath.com/blog/build-nodejs-express-stormpath-app/

Advantages:

I/O latency is crucial for implementing server.its not cpu bound operation. Most of the time , it goes in waiting for response.
so generally implementation is scaled with threading model( by running more threads concurrently for each request)
But for this, we will start getting following problems
-Context Switching OverHead
-Execution stacks take up memory
-Complicates concurrency

Some platforms used processes instead of threads to solve above problems
But it again it gets into
-High memory usage
-Process scheduling overhead

Node Internals:

Node Implementation scales with Event Loop
-Handles many concurrent requests in one process/thread
With this, it will get all i/o operations out of the way and gets into cpu bound operations.

                                          |  |                    __________
                                       |         |                | filesystem|
Event Queue                  |              |             |----------------|
 __________              |                   |            |  network   |
|__________|------>    |  Event Loop    |--------> |---------------|
|__________|              |                   |            |  process  | 
|__________|              ^|               |               |---------------|   
|__________|                  |        |                   |  other      |
|__________|                     |  |                      |_________|
     ^|                 Thread of node                              |    Thread Pool of underlying O.S.
      |_______________________________________|
     
Node Platform
                    node standard library (c code)
        ------------------------------------------------
                      node bindings (c code)
                    (http,socket, file system)
        ------------------------------------------------
         V8 | thread pool| event loop | crupto  | DNS
    (c code)| (libeio)   |  (libev)   | OpenSSL)| (c-ares)

Node is asynchronous even driven architecture. It has even loop through which it process the
events. Its single thread model.

Why JavaScript ?
- JavaScript has certain characteristics that make it very different than other dynamic languages, namely that it has
no concept of threads.Its model of concurrency is completely based around events.

While executing the code written in js, Node registers the events. and then Node goes in event loop(i.e. checking for events continuously).
When the particular event triggers (i.e. request event,response,connection,close etc.), Node runs the corresponding callback to take further action in application.


How Inheritance can be achieved in NodeJS example:

file1 :-> apirequest.js

var EventEmitter = require('events').EventEmitter;
var util = require('util');
function APIRequest(endpoint) { }
util.inherits(APIRequest, EventEmitter);
APIRequest.prototype.start = function() { }
module.exports = APIRequest;

file2 :-> feed.js

var util = require('util');
var APIRequest = require('../lib/api_request');

function Feed(endpoint) {
  APIRequest.call(this, endpoint);
}
util.inherits(Feed, APIRequest);
var feed = new Feed(endpoint);
feed.start();


how to resolve dependent packages ?

1) npm -> node package manager , dependent packages of existing application/package can be downloaded
using npm , it stores in global node_modules in node\lib\node_modules\npm\node_modules.
you need to use command require() to use in your application.
most of the packages are downloaded from github.
command -> npm install ( this access https://github.com to download pkgs)

2) If you want to manually install the dependency pkg. e.g aws-sdk.
visit github site and download required pkg. you can keep the code in global node_modules i.e
node\lib\node_modules\npm\node_modules. and update package.json kept at node\lib\node_modules\npm
accordingly to be used by application. and resolve the dependent pkgs accordingly.

3) If you don't want to keep it in global node_modules , you can create local node_modules folder inside
your application folder and keep the downloaded packages inside it. npm search algorithm locates 'node_modules'
folder in its parent directory hierarchy in turn which has relevant packages.
you can browser npm search alogo @ http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm

4)To resolve packages by name and version, npm talks to a registry website that implements the CommonJS Package Registry specification for reading package info.
The official public npm registry is at http://registry.npmjs.org/.

npm config set registry http://registry.npmjs.org/
npm install
OR
npm install --registry http://registry.npmjs.org/
If there is issue with SSL i.e. behind any corporate proxy/proxy which is causing problem for downloading packages.
you can set the registry to resolve packages.
This would download the required package and keep it 'node_modules' folder locally inside an application or in existing node_modules folder in parent hierarchy.


References:

(https://www.youtube.com/watch?v=L0pjVcIsU6A)
Node uses JavaScript as language to create servers. JavaScript v8 is better dynamic language compared to others.
Of Course, this is not faster than native language as c,java but faster than other dynamic language python,php,ruby etc..
http://benchmarksgame.alioth.debian.org/

No comments: