Search This Blog

2015-10-23

Managing HTTP request using Node JS

In this demo, we are going to look at how we can process a "POST" request that is going to come in with some form data within our Node application. And to do that, we are going to be using the help of the "connect" module and also the "body-parser" module.

Step 1: Run "npm init"

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

Step 3: In package.json , add the dependencies as below

"dependencies": {
"Connect": "*"
"body-parser":"*"
}


Step 4: in 'index.js', write the following code

var http=require('http');
var connect=require('connect');
var bodyParser=require('body-parser');

//bodyParser.urlencoded is going to make it easy for me to work with http form data by populating the body object of the http request that comes in, so I can //easily access that data.

var app=connect()
      .use(bodyParser.urlencoded(
        {extended:true}
       )
    )
      .use(function(req,res){
//Handler Method
var parsedInfo={};
parsedInfo.firstName=req.body.userFirstName;//
access the userFirstName and the userLastName properties of the body
parsedInfo.lastName=req.body.userLastName;

res.end("User Infor Parsed from: " +parsedInfo.firstName+" " + parsedInfo.lastName)
      }
);

 http.createServer(app).listen(3456);
 console.log("listening from 3456"); 

Step 5: Create a Html page with the following content


 

<html>
 <head>
 <title>User Infor From Page</title>
 </head>

 <body>
  <h2>Enter Detail and Submit</h2>
  <form action="http://localhost:3456" method="POST">
 First Name:<input Type="text" name="userFirstName"/>
 Last Name:<input Type="text" name="userLastName"/>
 <input type="submit" name="submit"/>
 </form>
 </body>
</html>

 User Info From Page
 
 
  

Enter Detail and Submit


  

 First Name:
 Last Name:
 
 

 

Step 6: run 'node index.js'

Step 7: Open the HTML page in browser, insert First & Last name and  submit the page.

Step 8:You will get the response in browser , as per the response object.

Creating an HTTP Server using Node JS

One of the purposes Node.js is commonly used for is creating HTTP servers capable of responding to client requests.

Step 1: Run "npm init"

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

Step 3: Create Http Server using 'createServer' method of 'http' module

var http=require('http');

var handlerMethod=function(req,res){
 res.end("Hello, This is a message from the handler of web server");
}

http.createServer(handlerMethod).listen(1234,'localhost');

console.log("Http Server is running");

Step 4: Run it using 'node index.js'

Step 5: open your brower and browse 'http://localhost:1234' to see the output.

It will display the message 'Hello, This is a message from the handler of web server' ,as mentioned in your response object.

2015-10-16

Node JS Modules

What is Module in Node JS

Modules make it possible to include other Javascript files into your applications. In fact, a vast majority of Node’s core functionality is implemented using modules written in JavaScript.

Using modules is simple: you use the require() function, which takes one argument: the name of a core library or a file system path to the module you want to load.

To make a module yourself, you need to specify what objects you want to export. The exports object is available in the top level scope in Node for this purpose.

Example, create hello.js and write the following code
 
exports.firstname='Manab';
exports.myfunction = function()
{  
return 'Hello World';
 
};
 
Then, in your index.js(calling Page),execute the module as below,
 
var hello = require('./hello.js');
console.log(hello.myfunction ()); // Print "Hello World"

 
But we also have the option of using the 'module.exports' to export just one single entity from our modules.

 

in hello.js

module.exports = function(){

//return Math.random();

return 'Hello World';
} 

 
In index.js
console.log(hello); // Print "Hello World"
 

Core modules :


Core modules that are provided by Node itself, examples are
 
1)var os = require ('os');
console.log(os);
console.log(os.platform());

2)var http = require('http');
console.log(http);

NPM Package Management  :

1)run 'npm init'.
2)Enter name, Version, Description and author and leave blank for other option to be defaulted.
3)It will generate package.json.
4)Manually create index.js as a default entry point
5)run 'npm install express --save'

The dependencies(in package.json) code block is as follows:
"dependencies": {
"express": "^4.9.6"
}



==>install 'express' which is getter than 4.9.6

6)run 'npm update' ==> after changing version of dependencies from package.json
7)run 'npm prune'  ==> after removing dependencies from package.json

 

NPM Modules :

This is the community modules find in the below location
https://www.npmjs.com/

Install the NMP modules after npm init and get a folder structure:

1)npm install underscore --save

var _ = require('underscore');
var names = ["Steve", "Stuart", "Ari", "Ayan"];
_.each(name, function(name){
console.log("Name is: " + name);
});


2)npm install    => if package.json(will get after npm init) contains the dependencies
 

Create Module(./)

Create fruit.js as below :

module.exports = function(name, description){
var name = name;
var description = description;
var functions = {
setName: function(nameIn)
{
this.description = description;
},
getInfo: function()
{
return{
name: name;
description: description;
}
}
};
return functions;
}



In Index.js

var fruit = require('./fruit.js');

var banana = fruit('banana', 'yellow fruit');
var cherry = fruit('cherry', 'small red fruit');
console.log(banana.getInfo());
console.log(cherry.getInfo());


 
 

Managing Node Version and Editor

Switching between different version of NodeJS:

Sometimes when we create our Node applications, it's going to be necessary to check or test our apps between different versions of Node just to make sure that everything is still working as expected.

Now there are a few tools that we can use to help us do this. If you are in a Linux based environment, you may use a tool such as NVM so that's a Node module. We are in a Windows based environment, so we are going to be using another Node module called NVMW as below.

[To test That, Create app.js and type console.log(process.version)  and execute it using 'node app.js' , before and after changing the current version]

C:\Manab>npm install -g nvmw

C:\Manab>nvmw install v0.10.26

C:\Manab>nvmw use v0.10.26

When I use nvmw in this command prompt, in the shell, it really is only valid for this shell.

To deactivate the older version in the current command prompt , just type below command :

C:\Manab>nvmw deactivate

Node JS Editor :

The Mostly used Editor is Sublime Text, could be downloaded from below location

http://www.sublimetext.com/

You could use , Node js Tools Visual Studio(NTVS) also as a NodeJS IDE