Search This Blog

2015-10-26

Serving a HTML file from Node JS

We can serve static files from the HTTP servers that we create using Node.js.

we are going to take advantage of two modules to do that. Those are the "connect" module and the "serve-static" module. So "connect" is an extensible HTTP framework that allows me to plug in additional functionality into my HTTP server and "serve-static" is one of the plug-ins that we are going to use to help us serve static files easily from our applications.

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 and run 'npm install'

{
  "name": "demostaticfile",
  "version": "1.0.0",
  "description": "Service Static Content from web server",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "MRB",
  "license": "ISC",
  "dependencies" : {
    "connect"         : "*",
    "serve-static"    : "*"
   
  }
}


Step 4: Create a folder 'public' under the root and place html and image files within the public folder.

Step 5: Write below code in your 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(7878);

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

Step 6: Open your browser and try browsing your test html file or image file

http://localhost:7878/test.html

2015-10-23

Creating a Node.js HTTP Client Application

This is useful when you are providing some sort of a proxy functionality or even some sort of web scraping type functionality where you are going to go out and grab web pages, and then attempt to process the HTML page, and get some information from it.

we are actually going to be using an external 'request' 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 and run 'npm install'

"dependencies": {
"request": "*"
}


Package.json:

{
  "name": "demohttpclientapp",
  "version": "1.0.0",
  "description": "create a http client application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "MRB",
  "license": "ISC",

  "dependencies": {
  "request": "*"
   }
}


Step 4:Write below code in your index.js

var request = require('request');
request('http://www.google.com', function(error, response, body){
if (!error && response.statusCode == 200){
console.log(body);
}
if (error){
console.log(error);
}
});

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

Configure responses from a Node.js web server

we can customize or configure the type of response that we send back in our application. And to help us in this demo, we are going to be using the "connect" module, which is a framework that's going to allow us to easily plug in functionality to our HTTP server.

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": "*"
}


Step 4 :

var connect=require('connect');

var app=connect()
.use(function(req,res){


 if(req.url == "/hello")
 {
  console.log("sending plain");
  res.end("Hello from app");
 }

 else if(req.url == "/hello.json")
 {
  console.log("sending json");
  var data = "Hello";
  var jsonData = JSON.stringify(data);
  res.setHeader('Content-Type', 'application/json');
  res.end(jsonData);
    }

 else if(req.url == "/hello404")
 {
  console.log("sending 404 status code")
  res.statusCode = 404;
  res.end("Oops, could not find something");
 }

res.end("I am listening");

})
.listen(1111);

console.log("listening at port 1111");

Step 5: Run the application by 'node index.js' and try 'http://localhost:1111/hello' in browser

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



NODE JS and MEAN Stack

What is Mean :
MEAN is an opinionated fullstack javascript framework - which simplifies and accelerates web application development.Mean Stands for MongoDB,Express,NojeJS and AngularJS.

What is MongoDB :
MongoDB is the leading NoSQL database, empowering businesses to be more agile and scalable.

What is Express :
Express is a minimal and flexible node.js web application framework, providing a robust set of features for building single and multi-page, and hybrid web applications.

What is Node JS :
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.It is an application development platform that allows us to create standalone applications developed using JavaScript.

What is AngularJS :
AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

Install NodeJS in windows:
Go to the https://nodejs.org/en/ and Click 'Download for Windows'. Once download completed, install it.

In odder to check the installation, Open the command prompt and type node -v , it will show you the current version of node js installed at your PC.

C:\>node -v

REPL :
In order to start the Read-Eval-Print-Loop or REPL for short, I am going to just type the node command and I'm not going to use any of the flags. And you can see now my cursor has changed here to the > sign, and now I am actually in the REPL. And at this point, I'm just basically free to start entering lines of JavaScript that are going to be evaluated right away.

I can say something like console.log("Hello World") and press Enter.

Also , the multiline REPL command executed be as below in while loop

When you have done, press Ctrl+c twice or type process.exit(1) , in oder to exit the REPL.


  • Read - Reads user's input, parse the input into JavaScript data-structure and stores in memory.
  • Eval - Takes and evaluates the data structure
  • Print - Prints the result
  • Loop - Loops the above command until user press ctrl-c twice

  •