Saturday 9 August 2014

create a application with node.js and express

Standard

today is nice day you have lot's of time so don't spend it or spoil it just do anything that will strong your skill.
so i have decide today i will discus about node.js how you create a basic app.
don't forget all project start from a basic app so if your basic and project basic is strong then project and your future not stop any how.

so question is how you will start your app already i have tolled you how you install node.js with express framework.


just follow that link:
http://netai-nayek.blogspot.in/2014/08/how-to-install-nodejs-with-express-in.html

follow all step before "express -s" command

ok first of all create a folder "node"(just for store all node file here) next go to this folder from terminal and follow bellow steps don't step jump because you don't know what is impotent .

next create a file "package.json".

The Express manifest file

create a package.json file in your app(node) folder
this file have lot's of dozen field but today i will tell you minimal field.
Here is what it should look like:

{
    "name":"store",
    "version":"0.0.1",
    "private":true,
    "description":"test project store",
    "scripts":{
        "start":"node app"
    },
    "dependencies":{
        "express":"3.x",
        "jade":"*"
    }
}

ok next open your terminal and go to node folder for start your node server and type bellow command:
$ npm install

after press enter you will lots of scrolling text after complete your install you will a directory(node_module) created in node folder . this is a node module here store all node module

auto generating express app

The process of creating the manifest file, the app.js file, the views, and other
directories and files can become a tedious chore as we start to work on multiple
projects. To automate this process, we can use the express command-line tool.
open terminal and go to your  app folder and type bellow command;

$ express -s

here also create lots of file and directory, next for test type:

$ node app

next open browser and type http://localhost:3000 and you will see your app basic page like 500 error page.

Express with middlewares

express middleware is a node module that we will use in express for few purpose like database,file,session,cookie,I/O and more. so what is basic middleware for your reference, the following is the list of the middlewares that are available in
Express, by default:

Express with Node modules

Express does not come packed with a huge bunch of built-in libraries to perform
tasks that are beyond a basic website. Express is very minimal. But that does not
mean that it is not capable of performing complex tasks. You have a huge collection of Node modules on the npm registry that can be easily plugged in to your app and used for performing all sorts of tasks in the app.
ok now i will tell how you will install a module , here i will create a config file for your app and it will parse by a external module in app.
open your terminal and go to app(node) folder and type bellow command:

$ sudo npm install iniparser
after install iniparser you will see a folder(iniparser) have created in your node_module folder.

create express config file

create a config.ini file in app(node) folder with bellow content.

title= My test app
port=3000
message=this is test project
Now edit app.js to include the module and use it in our app:

var express = require('express');
var app = express();
// Load the iniparser module
var iniparser = require('iniparser');
// Read the ini file and populate the content on the config object
var config = iniparser.parseSync('./config.ini');
//this is for template engine load your html file and parse with data
app.set('view engine', 'jade');
app.set('views', './views');
// this is for store your static file like css,js,images
app.use(express.static('./public'));
app.use(app.router);
app.use(express.errorHandler());
//this for page request function route handler callback function
app.get('/', function(req, res) {
// Pass two config variables to the view
    res.render('index', {title:config.title, message:config.message});
});
http.createServer(app).listen(config.port, function() {
    console.log('App started on port ' + config.port);
});
now create a jade.html file in views and save a image(logo.png) in public/images folder and write bellow content:

html
head
title #{title}
body
#content
img(src='images/logo.png')
p WELCOME
p #{message}

Understanding Express Routes

Routes are URL schema, which describe the interfaces for making requests to your web app. Combining an HTTP request method (a.k.a. HTTP verb) and a path pattern, you define URLs in your app.
Express, by default, supports the following HTTP request methods that allow us to define flexible and powerful routes in the app:

•     GET
•     POST
•     PUT
•     DELETE
•     HEAD
•     TRACE
•     OPTIONS
•     CONNECT
•     PATCH
•     M-SEARCH
•     NOTIFY
•     SUBSCRIBE
•     UNSUBSCRIBE

Defining routes for the app

we know how routes and route handler callback functions look like. Here is an
example:
app.get('/', function(req, res) {
  res.send('welcome');
});
Let's create a sample application to see if all the HTTP verbs are actually available as methods in the app object:
edit app.js file and type bellow content:

 app.use(app.router);
// GET request to the root URL
app.get('/', function(req, res) {
res.send('/ GET OK');
});
// POST request to the root URL
app.post('/', function(req, res) {
res.send('/ POST OK');
});
// PUT request to the root URL
app.put('/', function(req, res) {
res.send('/ PUT OK');
});
// PATCH request to the root URL
app.patch('/', function(req, res) {
res.send('/ PATCH OK');
});
// DELETE request to the root URL
app.delete('/', function(req, res) {
res.send('/ DELETE OK');
});
// OPTIONS request to the root URL
app.options('/', function(req, res) {
res.send('/ OPTIONS OK');
});
// M-SEARCH request to the root URL
app['m-search']('/', function(req, res) {
res.send('/ M-SEARCH OK');
});
// NOTIFY request to the root URL
app.notify('/', function(req, res) {
res.send('/ NOTIFY OK');
});
// SUBSCRIBE request to the root URL
app.subscribe('/', function(req, res) {
res.send('/ SUBSCRIBE OK');
});
// UNSUBSCRIBE request to the root URL
app.unsubscribe('/', function(req, res) {
res.send('/ UNSUBSCRIBE OK');
});
// Start the server
http.createServer(app).listen(3000, function() {
console.log('App started');
});

Route identifiers

So far we have been dealing exclusively with the root URL (/) of the app. Let's find out how to define routes for other parts of the app. Route identifiers can be string or regular expression objects.

// Will match /abcd
app.get('/abcd', function(req, res) {
  res.send('abcd');
});
// Will match /acd
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});
// Will match /abbcd
app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});
// Will match /abxyzcd
app.get('/ab*cd', function(req, res) {
  res.send('ab*cd');
});
// Will match /abe and /abcde
app.get('/ab(cd)?e', function(req, res) {
  res.send('ab(cd)?e');
});
//will match /user/3
app.get('/user/:id', function(req, res) {
res.send('user id: ' + req.params.id);
});

and also it's important to follow order depend on your requirement. 

Using Node modules

Create a directory named routes if not exist to keep our route handlers. In the directory, create two basic Node modules: index.js and users.js.
Here is the content for index.js:

exports.index = function(req, res){
res.send('welcome');
};

And, here is the content for users.js:

exports.list = function(req, res){
res.send('I am Netai Nayek');
};

Now, update the app.js file to include our route handlers:

var express = require('express');
var http = require('http');
var app = express();
// Load the route handlers
var routes = require('./routes');
var user = require('./routes/users.js');
// Add router middleware explicitly
app.use(app.router);
// Routes
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(3000, function(){
console.log('App started');
});

open terminal and go to app folder and type bellow command for start server:

$node app

Start the app and load http://localhost:3000 and http://localhost:3000/
users on the browser to see the results.
Now our route handlers reside in separate Node modules, making our app a little more modular. Can the app be made even more modular?
so now routes directory will called handlers, so go and rename routes folder to handlers and create a new file routes.js file in app directory and copy bellow command.

// Load the route handlers
var routes = require('./handlers');
var user = require('./handlers/users');
module.exports = function(app) {
// Define the routes
  app.get('/', routes.index);
  app.get('/users', user.list);
};
Now modify the app.js file to the new changes we have made:

var http = require('http');
var express = require('express');
var app = express();
// Explicitly add the router middleware
app.use(app.router);
// Pass the Express instance to the routes module
var routes = require('./routes')(app);
http.createServer(app).listen(3000, function() {
console.log('App started');
});
now restart your node server and open same in browser.

Sending data format

The component of an HTTP response message, which users can generally see and interact with, is called the body of the message. The body can come in many different forms—as HTML, plain text, images, binary files, CSS files
// this is for plain text
app.get('/', function(req, res) {
res.set('Content-Type', 'text/plain');
res.send('<h1>welcome</h1>');
});
//this is for html
app.get('/', function(req, res) {
res.send('<h1>welcome</h1>');
});
//this is for json data
app.get('/', function(req, res) {
res.json({message: 'welcome'});
});
//this is for jsonp
app.get('/', function(req, res) {
res.jsonp({message: 'welcome'});
});

serve error page

Displaying an error page can be as simple as sending just an error status code with no body, or rendering an elaborate 404 or 500 error page.
i think create error page like sophisticated.
write bellow code in app.js and create a html file 404.jade in view folder.
app.use(function(req, res) {
res.status(400);
res.render('404.jade',
{
title: '404',
message: 'File Not Found'
}
);
});

Redirecting a request

Sometimes you may want to redirect the request to a different URL, instead of
responding with data. This is made possible in Express using the res.redirect()
method.
The following are some examples of redirecting requests from an Express app:

jade template

it's a long story i will tell you later.  

handle Forms, Cookies, and Sessions data

form,cookies and session is the main part of website first of all you need to little knowledge on html then you will know how to create a form in node. ok lets start your app.
first of all edit and delete all content app.js file and copy bellow content to app.js

var http=require('http');
var express=require('express');
var redisStore=require('connect-redis')(express);
var iniparser=require('iniparser');
var config=iniparser.parseSync('./config.ini');
var fs=require('fs');

var app=express();
//parse your form sending or request data to your app
app.use(express.bodyParser({keepExtentions:true}));
//parse cookie data to your app
app.use(express.cookieParser());
//parse your session data
app.use(express.cookieSession({
        store:new redisStore({
                host:'127.0.0.1',
                port:5345,
                prefix:'sess',
            }),
        secret:'superkey'
    }));

var routes=require('./routes')(app);

app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(app.router);
app.use(express.errorHandler());
app.use(express.logger({
        format:'tiny',
        stream:fs.createWriteStream('app.log',{'flagd':'w'})
    }));
app.use(function(req,res){
        res.status(400);
        res.send('File Not Found');
    });

http.createServer(app).listen(config.port,function(){
        console.log('App started on port '+config.port)
    });
explanation of code:
 app.use(express.bodyParser({keepExtentions:true}));
 this is for parse your form sending data to your form

app.use(express.cookieParser());
parse your cookie data

app.use(express.cookieSession({
        store:new redisStore({
                host:'127.0.0.1',
                port:5345,
                prefix:'sess',
            }),
        secret:'superkey'
    }));
parse your session data

now create or edit routes.js file in app folder

var routes_index=require('./handlers');
var routes_search=require('./handlers/search');
var routes_signup=require('./handlers/signup');

module.exports=function(app){
        app.get('/',routes_index.index);
        app.get('/search',routes_search.search);
        app.post('/signup',routes_signup.signup);
    }
next create view file in handlers folder first create index.js file and copy bellow content.

exports.index = function(req, res){
//store data to session
    req.session.name='test test';

//store data to cookie
    res.cookie('email',"test@gmail.com");
    res.render('index',{title:'Welcome',message:'This is test'});
};


and create other file signup.js file and a "profile" folder in public/images folder

var fs1=require('fs');
exports.signup=function(req,res,fs){

//parse form data
        var name=req.body.name;
        var email=req.body.email;
        var profile_image=req.files.profile_image;
        var tmp_path=profile_image.path;
        var target_path='./public/images/profile/'+profile_image.name;

//store form sending file
        fs1.rename(tmp_path,target_path,function(err){
                if(err){next(err);}
                fs1.unlink(tmp_path,function(){
                        if(err){next(err);}
                        console.log('File Uploaded to: '+target_path+' - '+profile_image.size+' bytes');
                        console.log('Name: '+name);
                        console.log('Email: '+email);

//clear cookie
                        res.clearCookie('email');

//get cookie data
                        console.log(req.cookies.email);

//get session data
                        console.log(req.session.name);
                        res.redirect('/images/profile/'+profile_image.name);
                    });
            });
        //res.json(req.body);
};


explanation of code:
 var name=req.body.name;
parse form sending data in a variable

        fs1.rename(tmp_path,target_path,function(err){
                if(err){next(err);}
                fs1.unlink(tmp_path,function(){
                        if(err){next(err);}
                        console.log('File Uploaded to: '+target_path+' - '+profile_image.size+' bytes');
                        res.redirect('/images/profile/'+profile_image.name);
                    });
            });
store form uploaded file from temp folder to in folder

res.clearCookie('email');
clear cookie data

        console.log(req.cookies.email);
        console.log(req.session.data);
get session and cookie data

now create index html file in view folder create a file index.jade file in view folder and copy bellow code in file. here you will see how inherit a template in other template

extends layout

block head
    script(src="./js/jquery.js")
block content
    img(src='images/logo.jpg' height="100")
    p WELCOME
    p #{message}
    form(action="/signup",method='post',enctype="multipart/form-data")
        div
            label Name
            input(type="text",name="name")
        div
            label Email
            input(type='text',name='email')
        div
            label Profile Image
            input(type="file",name="profile_image")
        div
            input(type='submit',value='Send')

block footer
    #footer Copyright &copy; 2014
now create a layout.jade file

html
    head
        title #{title}
        link(rel='stylesheet',href='./css/style.css')
        block head
    body
        #content
            block content
        block footer


now start your server type in terminal

$node app

and open browser and type http://localhost:3000

then open a screen like bellow
and after fill all field , when you submit, then open your uploaded image and you will see in terminal like.


ok now you have create again your new cocktail now just drink it and enjoy.

dont stop go forward