Package Manger in Node.js


The Package manager is like a library for Node.js. From this package manager the classes and function can be importable . The node has repository  www.npmjs.org to upload and download modules for Node.js. The most interesting modules are express and mongodb and more.

We have to install npm manager in our machine .usually this will automatically installed when we install the node.js. If not we can download install the npm manager using linux terminal command
sudo apt-get install npm

Also each module has it’s own website. Which describe the module functions and the classes. For example we have a module call underscore and also this has own page call www.underscore.org this supports lots fo libraries in JavaScript.

After the installation of the npm Package manager we can download the module using the linux terminal command
1) Go to project directory using linux terminal
2) In terminal command : npm install underscore ( underscore is the name of the package)
3) It will go to npm registry, fetch and download into your directory which is a node_module directory. which contain       underscore (Library ) source code
4) If you import the module into your project directory then it can be automatically importable in projects using,
var name = require(“underscore”) // underscore is just a library name

The module read the details using package.json which is in the module directory.

ERROR:
node.js:201
       throw e; // process.nextTick error, or 'error' event on first tick
             ^
Error: Cannot find module 'graceful-fs'
   at Function._resolveFilename (module.js:334:11)
   at Function._load (module.js:279:25)
   at Module.require (module.js:357:17)
   at require (module.js:368:17)
   at Object.<anonymous> (/usr/share/npm/lib/utils/ini.js:32:10)
   at Module._compile (module.js:432:26)
   at Object..js (module.js:450:10)
   at Module.load (module.js:351:31)
   at Function._load (module.js:310:12)
   at Module.require (module.js:357:17)
dhanushanth@ubuntu:~$

If you got any error like above . Then the problem is with the older version of node. So you need to update the node.js version or we have another solution as well.

Solution : This will install the npm according to our node.js version

git clone git://github.com/isaacs/npm.git
cd npm/scripts
chmod +x install.sh
sudo ./install.sh


Npm library global installation
Another place that we can install the node_module globally which means that we can install this once as global
To install that command in terminal,
sudo npm install underscore -g

After the installation we can update the module using below command,
npm update _PackageName_


Search for package
In www.npmjs.org we can search for packages in search package after the search we just need to get the name of the package and install the module using the same way that we have done for unsercore


Note: Always check the updates of the package doc for changes. Because according the update the classes and function calling may be chage.

Import_Config_file_NodeJs


Here we can make our work more easier because we can list our data in json file and call the needed data in application. In this example I defined the host and port address in config file and call the values in my project file. Also here we are using watch class from file system module. This is very help full in real time server management. Because without stopping the server the port and host address can be changeable. For example if we have the address for the host and port in config.json then it can be update in realtime without stopping the server.

Sample of config file
save as config.json (name can be vary)
{
"port" : 1336,
"host" : "127.1.1.1"
}


var http = require("http");

var file = require("fs");

console.log("Starting");

/* Call the JSON formatted config file to read the host and port values . Here we used the readFileSync class from File system module. The FileSync class use to make wait the bellow code until it read the config file - After Sync only the other code will proceed */
var config = JSON.parse(file.readFileSync("config.json"));

// Host and Port Address which are read from config
var host = config.host;
var port = config.port;

var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);
//here “.” space we have to define our file path Ex: ./Dir
file.readFile("." + request.url,
function(error,data){
if(error){
response.writeHead(404,{"Content-type":"text/plain"});
response.end("Sorry the page was not found");
}else{
response.writeHead(200,{"Content-type":"text/Html"});
response.end(data);
}
});
});

server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);



/*The watchFile class is automatically search for any changes in config file with the frequent time interval. If it get any update from that file. Then it will return to the system with the changes*/
file.watchFile("config.json",
function(){
config = JSON.parse(file.readFileSync("config.json"));
server.close();
host = config.host;
port = config.port;
//Listen to newport when we update the config.json file
server.listen(port,host,
function(){
console.log("New listening " + host + ":" + port);
});
});



HTML or File call in Node.js


Before to Start please read the 3_Http_Request Doc. This is use to read a html file which is in our disk. push in to browser according to client request.

var http = require("http");
// Import File system module to read the file
var file = require("fs");

console.log("Starting");

var host = "127.1.1.1";
var port = 1337;

/* Creating a callback which fired every single request that contain the url from client request and response is similar as request*/
var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);

//After we receive the file then we have to read the file from the request URL
file.readFile("." + request.url,
function(error,data){
/* Here we have error object and Data Object in function. So error and data can be return to that specific variables. Therefore If we have error we have to respond to user with predefined String else we have to return the file*/
if(error){
//404 is the status code for not found
response.writeHead(404,{"Content-type":"text/plain"}); response.end("Sorry the page was not found");
}else{

//here our file system is Html so the content type is html
response.writeHead(200,{"Content-type":"text/Html"});
response.end(data);
}
});
});

server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);

After the code completes,
1) Go to project directory using terminal
2) command : node fileName.js
3) If the server starts Go to web browser and  type http://127.0.0.1:1337/name.html
4) you will get the result as html page or error message depend on the request in browser.


HTTP Request In Node.js


Here we are request a server with defined host and port to get a response from server. This is basically created by callback function (non-blocking). Also here I mentioned some modules. The modules can be explained in coming posts.

// Importing the HTTP module from node_module
var http = require("http");

// Print some text to check the start
console.log("Starting");

// Host and Port Address
var host = "127.1.1.1";
var port = 1337;

/* Creating a callback function which fired every single request that contain the url from client request and response is similar as request. here we are importing the createServer class from http module(http.createServer)*/
var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);
response.writeHead(200,{"Content-type":"text/plain"});
response.end("Hello");
}
);

//Server Listening
server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);

After completing this code ,
1) Go to project directory using terminal
2) command : node fileName.js
3) If the server starts Go to web browser and  type http://127.0.0.1:1003
4) you will get the “Hello” in browser.

Node.js Installation



To install node.js we need to install dependencies
-----------------------------------------------------------------
apt-get update
sudo apt-get install libssl-dev
sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core
Check the python version as well

Note: There has some possibility to have an error  when we try to install the node Because of the Dependencies .So Please recheck the dependencies

Install from the downloaded version of node from node site
----------------------------------------------------------------------------------
tar -zxf node-v0.6.18.tar.gz #Download this from nodejs.org
cd node-v0.6.18
./configure && make && sudo make install


Clone node.js from github and installation process
----------------------------------------------------------------------
git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install


Test the version and conformation of installtion
------------------------------------------------------------------
node --version //This will print the version of the node.js


Node as a real time console
--------------------------------------
Here we can check the single code or any command with node command prompt. For that in terminal text “node” Then automatically the command prompt redirect to node.js console for real . To print some line “hello node.js” in command prompt.

Example:
dhanushanth@ubuntu:~/node$ node
> console.log('hello Node.js')
hello Node.js


Run external .js files using node
--------------------------------------------
Say If the Java script file name is helloPrint.js then,
To run using terminal:
node helloPrint.js

If any issue with installation feel free to mail : dhanu.chrish@gmail.com

Why Node.js



Why Node .js?
This is basically focused on performance. Node performs the best for client’s response for servers. Say we have 100 concurrent clients and 1 megabyte of response. According that the node will have 833 Req/sec. This is comparably very fast response rather than ngins and thin. For this kind of thing we have some option call Sync and un-Sync options. We can see that later in this progress Document.
Code Comparison between Node and PHP.
For a Request,
Query in PHP.
result =query('select * from T')
The above single line of query may blocks the entire process somewhere or implies multiple execution stacks Until it get the response of the DB. Because the query is accessing the disk for an information. But when is come to the Ram and L1, L2 caches those are non-blocking processes. So we can increase our performance when we keep the application request in that level.
So the solutions for the above blocking issue are,
Option 1: Multitasking
Option 2: Other threads of execution can run while waiting
Through the event looping we can process the query efficiently.
query('select..',function(result){
        //use result
});
The above line allows the program to return to the event loop immediately using the callback function. Here No machinery required
The beauty of this event looping and callback is we can use this according to our needs (block or un-block),
For example:
We need to stop the process until we read any specific config file or specific name for the process. So for that we have to do some waiting event.
>In cultural Base
puts("Enter your name ");
var name = gets();
puts("Name : " + name);
The above sample code is asking for a user name. Until it receives the using name the other lines will not process. But again we have another problem if we have 1000 users online. And those 1000 users waiting to enter their names like this then think about the server load as that time. So here the callback plays the role to execute other line until is wait for some specific functions.
Using callback function,
puts ('Enter your name');
gets(function (name){
puts("Name :" + name);
});
But again the rejection is so complicated. Then why everyone using event loops? Because single threaded event loops require I/O to be non-blocking. We can access the disk without blocking. ruby python are event based programming languages. But the according to the user increases we need some expert knowledge of event loops. The JavaScript designed specifically to be used with an event loop and amazing thing
-Anonymous function, closures
-Only one callback at a time
-I/O through DOM event callbacks
The node.js project is to provide a purely evented non-blocking infrastructure to script highly concurrent programs.
Node JS Design goals
No function should directly perform I/O
To receive info from disk, network, or another process there must be a callbacks.
The Node is process based on Stack
ev_loop()->socket_readable(1)->http_parse(1)->load("index.html") So node sends request to the thread pool to load "index.html" and the request is send to disk In the mean time it will call the socket_readable(2) until the socket_readable(1) response. If the socket_readable(1)response then it will return file_loaded() in stack as bellow ev_loop -> file_loaded() ->http_respond(1) it means is respond to first request
Reference:
Nodes Conference 2012 - Click
Ryan Dahl (Creator of Node.js) Introduction speech - Click
Bruno Terkaly of Microsoft workshop - Click