Sunday, September 16, 2018

NodeJS 32: SocketIO -> ChatApp

NodeJS 32: SocketIO -> ChatApp






#######################################CODE##################################



#################################
index.html
#################################
<html>
<head>

<title>Chat App</title>
<!-- bootstrap cdn -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- jquery cdn -->
<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

  <!-- client side socket io -->
  <script src="/socket.io/socket.io.js"></script>

  <style>
    body{
        margin-top:30px;
    }
 </style>
</head>
<body>
    <div class="container">
            <div class="row">
                <div class="col-md-4">
                       <div class="well">
                           <h3>Online users</h3>
                           <ul class="list-group" id="users"></ul>
                       </div>
                </div>
                <div class="col-md-8">
                        <div class="chat" id="chat"></div>
                        <form id="messageForm">
                            <div class="form-group">
                                <label>Enter Message</label>
                                <textarea class="form-control" id="message"></textarea>
                                <br/>
                                <input type="submit" class="btn btn-primary" value="Send Message"/>
                            </div>
                        </form>
                </div>
            </div>
        </div>

        <script>
        $(function(){
               var socket=io.connect();//new connection to server
               var $messageForm=$('#messageForm');
               var $message=$('#message');
               var $chat=$('#chat');
               $messageForm.submit(function(e){//event handler for submit button click
                   e.preventDefault(); //disable default click event
                   socket.emit('send message',$message.val());//trigger 'send message' event
                    $message.val('');     
                   console.log('submitted');
               });

                //listen for new message from server
                socket.on('new message',function(data){
                  $chat.append('<div class="well">'+data.msg+'</div>');
               });

           });
        </script>
</body>

</html>


#################################
server.js
#################################
var express=require('express');
var app=express();
var server=require('http').createServer(app);
var io=require('socket.io').listen(server);

users=[];
connections=[];

server.listen(3000);
console.log('server listening on 3000');

app.get('/',function(req,resp){
resp.sendFile(__dirname+'/index.html');
});

io.sockets.on('connection',function(socket){//when user connects to the chat server
    connections.push(socket);
    console.log('Connected : %s socket connection',connections.length);
    socket.on('disconnect',function(){//when user disconnects from the chat server
        connections.splice(connections.indexOf(socket),1);
        console.log('Disconnected : %s socket connection',connections.length);
    }) ;

    //once user click on send -> this will trigger
    socket.on('send message',function(data){
        console.log(data);
        io.sockets.emit('new message',{msg:data});//then server emits this message to broadcast to all users
 });

});


#################################
package.json
#################################
{
  "name": "mychatapp",
  "version": "1.0.0",
  "description": "mychatapp",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "pavan",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "socket.io": "^2.1.1"
  }
}





#################################CODE END#################################






NodeJS 31: UnitTesting with NodeJS - Mocha & Chai

NodeJS 31: UnitTesting with NodeJS - Mocha & Chai





########################################CODE##############################


###############################
test.js
###############################
var chai=require('chai');
var expect=chai.expect;

chai.should(); //activate assertion framework on mocha engine

function returnName(name){
return name;
}

function addNumbers(num){
return num+num;
}
function IsEven(inputVal){
return (inputval % 2)===0;
}


describe('Math Operation',function(){
    it('Returns a value added to itself',function(){
      addNumbers(5).should.equal(10);
  });
  it('Should return true for even number',function(){
    IsEven(4).should.equal(true);
    });
});

//test case
describe('1st unit test',function(){
  it('Returns the name passed',function(){
returnName('Amit').should.equal('Amit');
    });
});



###############################
app.js
###############################
module.exports=function(){
return 'hello';
}

###############################
appTest.js
###############################
const assert=require('chai').assert;
const app=require("../app");

describe('App',function(){
it('app should return hello..',function(){
assert.equal(app(),'hello');
    });
   
    it('app should return string..',function(){
assert.typeOf(app(),'string');
});

});




###############################CODE END ###############################

NodeJS 30: BuildTook with NodeJS - Using GULP

NodeJS 30: BuildTook with NodeJS - Using GULP


#################################CODE########################################



#############################
gulpfile.js
#############################
var gulp=require('gulp');

var uglify=require('gulp-uglify');


gulp.task('scripts',function(){
gulp.src('src/*.js').pipe(uglify()).pipe(gulp.dest('dist'));
});


#############################
package.json
#############################
{
  "name": "automation",
  "version": "1.0.0",
  "description": "automation",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "pavan",
  "license": "ISC",
  "dependencies": {
    "gulp": "^3.9.1",
    "gulp-uglify": "^3.0.1"
  }
}




#############################
first.js
#############################
function myFirstFunction(){
return "first";
}


#############################
second.js
#############################
function mySecondFunction(){
return "second";
}



#############################CODE END#############################

NodeJS 29: BuildTook with NodeJS - Using GRUNT

NodeJS 29: BuildTook with NodeJS - Using GRUNT



#######################################CODE################################



######################
Gruntfile.js
######################
module.exports=function(grunt){
//trying to merge multiple js and send it to client as one file
//when we run the command it does automatically
grunt.initConfig({
concat :{  //to concatinate all js files in to 1 file
js: {
src: ['js/1.js', 'js/2.js'],
dest: 'build/js/scripts.js',
},
css: {
src: ['css/1.css', 'css/2.css'],
dest: 'build/css/styles.css',
}
},
watch:{  //to watch for file changes and execute
js:{
files: ['js/**/*.js'],
tasks: ['concat:js'], //to call only contact : js
},
css:{
files: ['css/**/*.css'],
tasks: ['concat:css'], //to call only contact : css
}
}
 });

//load this module
grunt.loadNpmTasks('grunt-contrib-concat');
//load this module
grunt.loadNpmTasks('grunt-contrib-watch');

//to automatically execute add it in 'default' section..
//CMD : grunt
 grunt.registerTask('default',['concat','watch']);

}


######################
package.json
######################
{
  "name": "grunt1",
  "version": "1.0.0",
  "description": "grunt",
  "main": "1.js",
  "dependencies": {
    "grunt": "^1.0.3",
    "grunt-cli": "^1.3.1",
    "grunt-contrib-concat": "^1.0.1",
    "grunt-contrib-watch": "^1.1.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "pavan",
  "license": "ISC"
}






######################CODE END ############################################

NodeJS 28: BuildTook with NodeJS (GRUNT & GULP)

NodeJS 28: BuildTook with NodeJS (GRUNT & GULP)




NodeJS 27: Input Validation - 'joi' module

NodeJS 27: Input Validation - 'joi' module


NodeJS 26: Project2: Online Music store

NodeJS 26: Project2: Online Music store


Requirement:
-------------------------------------
1. Page 1: Add music to cart
2. Page 2: Verify list of musics added.


Used: below database to push added musics and retrieve.

mongodb://test123:Pass123@ds257752.mlab.com:57752/todopavanmr 






###################################################################################################
package.json
###################################################################################################

{
  "name": "shoppingcart",
  "version": "1.0.0",
  "description": "shopping cart for music tracker",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "pavan",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "ejs": "^2.6.1",
    "express": "^4.16.3",
    "mongoose": "^5.2.15",
    "nodemon": "^1.18.4"
  }
}

###################################################################################################
app.js
###################################################################################################

var express=require('express');
var todoController=require('./controller/todoController');

var app=express();

app.use(express.static('./public'));

app.set('view engine','ejs');


todoController(app);

app.listen(3000);
console.log('listening on 3000');

###################################################################################################
todoController.js
###################################################################################################

var bodyParser=require('body-parser');
var mongoose=require('mongoose');

//connect to Mongodb on the cloud
mongoose.connect('mongodb://test123:Pass123@ds257752.mlab.com:57752/todopavanmr',{useNewUrlParser: true});

//create database schema as an object | ORM
var todoSchema=new mongoose.Schema({
    item:String
});

//Set the schema as the Model in the MVC Pattern
var Todo=mongoose.model('Todo',todoSchema);

//var data=[{item:'get milk'},{item:'walk the dog'},{item:'learn Nodejs'}];
var urlencodedParser=bodyParser.urlencoded({extended:false});

module.exports=function(app){

    app.get('/todo',function(req,resp){
        console.log("Inise get todo.....");
       Todo.find({},function(err,data){
           if (err) throw err;
           resp.render('todo',{todos:data});
       });
    });

    app.post('/todo',urlencodedParser,function(req,resp){
        console.log("Inise post todo.....");
       //data.push(req.body);
       var newTodo=Todo(req.body).save(function(err,data){
           if(err) throw err;
           resp.render('todo',{todos:data});
       });
    });

    app.delete('/todo/:item',function(req,resp){
        console.log("Inise delete todo.....");
        Todo.find({item:req.params.item.replace(/\-/g," ")}).remove(function(err,data){
            if(err) throw err;
            resp.render('todo',{todos:data});
        });
    });

    app.get('/checkout',function(req,resp){
        console.log("Inise get checkout.....");
        //resp.render('checkoutList',{todos:data});
        Todo.find({},function(err,data){
            if (err) throw err;
            resp.render('checkoutList',{todos:data});
        });
 
    });

};

###################################################################################################
todo.ejs
###################################################################################################
<html>
    <head>
        <title>Music Shopping</title>
        <script
        src="https://code.jquery.com/jquery-3.3.1.js"
        integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
        crossorigin="anonymous"></script>

        <script src="/assets/todo-list.js"></script>

        <link href="/assets/todostyles.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <h1>My Todo List</h1>
        <h4></h4>
        <div id="todo-table">
              <form>
                  <input type="text" name="item" placeholder="Add music track...." required/>
                  <button type="submit">Add to cart</button>
                </form>
              <ul>
                 <% for(var i=0; i < todos.length ;i++) { %>
                        <li><%=todos[i].item%></li>
                 <% } %>
              </ul>

           
           
              <!-- <form id="contact-form" method="GET" action="/checkout"></form> -->
                <table>
                    <tr>
                         
                            <button ><a href="/checkout" style="color:white">Checkout</a></button>
                            <!-- <input type="submit" name="submit" value="Checkout"/> -->
                            <!-- <span>You have added <%=todos.length%> items in your cart</span> -->
                    </tr>
                </table>
            <!-- </form> -->
             
             
           
             
         
        </div>
    </body>
</html>

###################################################################################################
checkoutList.ejs
###################################################################################################
<html>
    <head>
        <title>Checkout List</title>
        <script
        src="https://code.jquery.com/jquery-3.3.1.js"
        integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
        crossorigin="anonymous"></script>

        <script src="/assets/todo-list.js"></script>

        <link href="/assets/todostyles.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <h4></h4>
        <div id="todo-table">
        <h2>You have added <%=todos.length%> items in your cart </h2>
     
            <ul>
                    <% for(var i=0; i < todos.length ;i++) { %>
                           <li><%=todos[i].item%></li>
                    <% } %>
                 </ul>
               
                 <button type="submit"><a href="/todo" style="color:white">Back</a></button>
                 <button type="submit">Continue Payment</button>
    </div>
    </body>
</html>

###################################################################################################

todo-list.js

###################################################################################################

$(document).ready(function(){           //wait for the page to load

    $('form').on('submit',function(){   //resgister for submit button click in form
      
        var item= $('form input');      //get ref to the text box on the form
        var todo={item: item.val()};    //custom obj (item)= textbox value enteretd by the user
       
        $.ajax({                        //Async scope starts to fire async request to the server
            type: 'POST',               //send data in the body
            url: '/todo',
            data: todo,                 //data to be inserted (comes from textbox)
            success: function (data){   //if all ok, refresh the page to display inserted data
                location.reload();      //refreshes the page
            }
        });
        return false;                   //return false on faliure
    });

    $('li').on('click',function(){
        var item=$(this).text().replace(/ /g,"-");//clean the data of spaces
        $.ajax({                        
            type: 'DELETE',              
            url: '/todo/' + item, //append the item the user has clicked on to the url
            success: function (data){   
                location.reload();      //refreshes the page
            }
        });
    });

    // $('a').on('click',function(){
    //     //var item=$(this).text().replace(/ /g,"-");//clean the data of spaces
    //     $.ajax({                        
    //         type: 'GET',              
    //         url: '/checkout', //append the item the user has clicked on to the url
    //         success: function (data){   
    //             location.reload();      //refreshes the page
    //         }
    //     });
    // });


  

});


###################################################################################################
todostyles.css
###################################################################################################

body{
    background: #fefeff;
    font-family: tahoma;
    color: #f0f0f0;
}

#todo-table{
    position: relative;
    width: 95%;
    background: #495f81;
    margin: 0 auto;
    padding: 20px;
    box-sizing: border-box;
}

#todo-table form:after{
    margin: 0;
    content: '';
    display: block;
    clear: both;
}

input[type="text"]{
    width: 70%;
    padding: 20px;
    background:#a2bce2;
    border: 0;
    float: left;
    font-size: 20px;
    color: #d4d3d3;
}

button{
    padding: 20px;
    width: 30%;
    float: left;
    background: #2e6650;
    border: 0;
    box-sizing: border-box;
    color: #fff;
    cursor: pointer;
    font-size: 20px;
}

ul{
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li{
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    font-family: arial;
    font-size: 20px;
    cursor: pointer;
    letter-spacing: 1px;
}

li:hover{
    text-decoration: line-through;
    background: rgba(0,0,0,0.2);
}

h1{
    background: url(/assets/logo2.jpg) no-repeat center;
    margin-bottom: 5;
    text-indent: -10000px;
    height:90px;
    width: 1200px;
}

h4{
    background: url(/assets/navigation.png) no-repeat center;
    position:relative;
    display: inline-block;
    margin:0 25px;
    padding:0 10px;
    height:110px;
    width: 1200px;

}



###################################################################################################


















NodeJS 25: Project - "ProductBacklog" -> Step by Step

NodeJS 25: Project - "ProductBacklog" -> Step by Step

Project – Product Backlog


Step1: Create folder “ProductBacklog” -> and open it in “Visual Studio code”
Step2: Create “package.json” -> npm init
Step3: install Express server. -> npm install express –save
Step4: Create public/assets folder
Step5: install “nodemon” -> npm install nodemon -save
Step6: need to install “EJS” as view engine -> npm install ejs –save
Step7: install body parser for POST req handling -> npm install body-parser –save
Step8: create app.js -> set up all layers (Express -> Middleware -> EJS (view engine)
Step9: create todoController.js -> write .get , post, delete
Step10: create ‘todo.ejs’ (view) and ‘todo-list.js’ (jquery to invoke AJAX call)
Step11: Run the app.js -> node app    OR   nodemon app
Step12: Install MongoDB locally or in Cloud -> mlab.com -> sign up -> create database “todopavanmr” and copy paste the URL
Step13: Install mongoose to connect to MongoDB -> npm install mongoose –save
Step14 : Run app.js -> Test UI -> try inserting deleting the records from mongoDB.

##########################################################################

Step1: Create folder “ProductBacklog” -> and open it in “Visual Studio code”


Step2: Create “package.json” -> to keep track of all versioning, acts like LOG file when we move project from DEV env to PROD env helps.

npm init


Step3: We need Server to host our project so install Express server.

npm install express –save


Step4: Create public/assets folder -> to keep all static files.


Add “logo.png” and “todostyles.css” under assets folder


Step5: Since we are developing that in dev env, to monitor need to install “nodemon

npm install nodemon -save


Step6: Since we are going to use our own “View engine” -> EJS , need to install “EJS”

npm install ejs –save


Step7: to handle all POST request, we need to install body-parser

npm install body-parser –save


Step8: create ‘app.js’ and set up all layers (Express -> Middleware -> EJS (view engine)


Step9: create ‘todoController.js’


Step10: create ‘todo.ejs’ (view) and ‘todo-list.js’ (jquery to invoke AJAX call)
todo.ejs -> is view layer to display data, should be inside /views folder always
todo-list.js -> jquery , to call AJAX and reload page/component back.



Run the app.js

node app    OR   nodemon app



Now to push/get from DB
è We need to install MongoDB locally or in Cloud
è Use driver to communicate to mongoDB , using Mongoose (acts like driver and ORM tool -> automatically maps Entity to database tables just like Hibernate)
d

è We need to install MongoDB locally or in Cloud




mlab.com
sign up








mongodb://<dbuser>:<dbpassword>@ds257752.mlab.com:57752/todopavanmr




è Use driver to communicate to mongoDB , using Mongoose (acts like driver and ORM tool -> automatically maps Entity to database tables just like Hibernate)


npmjs.com

mongoose  - acts   like
- Driver
- ORM

npm install mongoose –save


mongodb://test123:Pass123@ds257752.mlab.com:57752/todopavanmr


Insert Item from UI -> to insert in to MongoDB and refresh below list.





################################################################################

package.json

{
"name": "productbacklog",
"version": "1.0.0",
"description": "product backlog tracker",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "pavan",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.6.1",
"express": "^4.16.3",
"mongoose": "^5.2.14",
"nodemon": "^1.18.4"
}
}

todostyles.css

body{
background: #1d2c44;
font-family: tahoma;
color: #989898;
}

#todo-table{
position: relative;
width: 95%;
background: #090d13;
margin: 0 auto;
padding: 20px;
box-sizing: border-box;
}

#todo-table form:after{
margin: 0;
content: '';
display: block;
clear: both;
}

input[type="text"]{
width: 70%;
padding: 20px;
background:#181c22;
border: 0;
float: left;
font-size: 20px;
color: #989898;
}

button{
padding: 20px;
width: 30%;
float: left;
background: #23282e;
border: 0;
box-sizing: border-box;
color: #fff;
cursor: pointer;
font-size: 20px;
}

ul{
list-style-type: none;
padding: 0;
margin: 0;
}

li{
width: 100%;
padding: 20px;
box-sizing: border-box;
font-family: arial;
font-size: 20px;
cursor: pointer;
letter-spacing: 1px;
}

li:hover{
text-decoration: line-through;
background: rgba(0,0,0,0.2);
}

h1{
background: url(/assets/logo.png) no-repeat center;
margin-bottom: 0;
text-indent: -10000px;
}
         
app.js

var express=require('express');
var todoController=require('./controller/todoController');

var app=express();

app.use(express.static('./public'));

app.set('view engine','ejs');


todoController(app);

app.listen(3000);
console.log('listening on 3000');             


todoController.js

var bodyParser=require('body-parser');
var mongoose=require('mongoose');

//connect to Mongodb on the cloud
mongoose.connect('mongodb://test123:Pass123@ds257752.mlab.com:57752/todopavanmr',{useNewUrlParser: true});

//create database schema as an object | ORM
var todoSchema=new mongoose.Schema({
item:String
});

//Set the schema as the Model in the MVC Pattern
var Todo=mongoose.model('Todo',todoSchema);

//var data=[{item:'get milk'},{item:'walk the dog'},{item:'learn Nodejs'}];
var urlencodedParser=bodyParser.urlencoded({extended:false});

module.exports=function(app){
app.get('/todo',function(req,resp){
Todo.find({},function(err,data){
if (err) throw err;
resp.render('todo',{todos:data});
});
});

app.post('/todo',urlencodedParser,function(req,resp){
//data.push(req.body);
var newTodo=Todo(req.body).save(function(err,data){
if(err) throw err;
resp.render('todo',{todos:data});
});
});

app.delete('/todo/:item',function(req,resp){
Todo.find({item:req.params.item.replace(/\-/g," ")}).remove(function(err,data){
if(err) throw err;
resp.render('todo',{todos:data});
});
});

};

todo.ejs

<html>
<head>
<title>Product Backlog</title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>

<script src="/assets/todo-list.js"></script>

<link href="/assets/todostyles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>My Todo List</h1>
<div id="todo-table">
<form>
<input type="text" name="item" placeholder="Add new Item...." required/>
<button type="submit">Add Item</button>
</form>
<ul>
<% for(var i=0; i < todos.length ;i++) { %>
<li><%=todos[i].item%></li>
<% } %>
</ul>
</div>
</body>
</html>

todo-list.js

$(document).ready(function(){ //wait for the page to load
$('form').on('submit',function(){ //resgister for submit button click in form
var item= $('form input'); //get ref to the text box on the form
var todo={item: item.val()}; //custom obj (item)= textbox value enteretd by the user
$.ajax({ //Async scope starts to fire async request to the server
type: 'POST', //send data in the body
url: '/todo',
data: todo, //data to be inserted (comes from textbox)
success: function (data){ //if all ok, refresh the page to display inserted data
location.reload(); //refreshes the page
}
});
return false; //return false on faliure
});

$('li').on('click',function(){
var item=$(this).text().replace(/ /g,"-");//clean the data of spaces
$.ajax({
type: 'DELETE',
url: '/todo/' + item, //append the item the user has clicked on to the url
success: function (data){
location.reload(); //refreshes the page
}
});
});
});