Node.Js : Success stories


Node.Js is quite new to server side scripting compared to Java, ASP.NET, PHP many other languages. But the interesting thing is it has gained a huge interest of developers over other server side scripting languages.There are a lot of reasons for that.

Here are few reasons for popularity of Node.Js,
  • Asynchronous and Event Driven
  • Very Fast
  • Single Threaded but Highly Scalable
  • No Buffering
But I'm not going to talk about those things. There are some interesting stories about Node.Js

Here are stories about what world's popular companies gained by using Node.Js (Obtained from a talk of Greg Rewis)

Getting start with Express: creating a HTTP server with express Js

Express is a minimal and flexible Node.js web application framework. It's the most popular framework as of now (the most starred on NPM). So Express make easy writing node.js programs.

First of all you should have node.js installed.

Here is how a simple HTTP server can be implemented with Express.

Initial setup

First Express should be installed globally and locally with NPM. If you have installed express ignore these two steps.

  1. Install Express globally with NPM(Node Package Manager)
    npm install -g express
  2. Install express locally
    npm install express
    npm install express --save if you using a package.json file to track your project

Repeating HTML elements in AgularJs

When we want to use a set of HTML elements repeatedly in our AngularJs application there is a basic directive called "ng-repeat"

Here is a set of examples for using "ng-repeat" directive

Example 1


<!DOCTYPE html>
<html>
<script src="scripts/angular.min.js"></script>
<body>
<div data-ng-app="" data-ng-init="names=['employee1','employee2','employee3']">
  <p>Looping with ng-repeat:</p>
  <ul>
    <li data-ng-repeat="employee in names">
      {{ employee }}
    </li>
  </ul>
</div>
</body>
</html>

NodeJs : CRUD operations on a SQL database


Doing CRUD (CReate, Update, Delete) operations on a database is necessary part in a normal web application. Here is how it can be done using powerful node.Js framework.

First a connection has to be made in-order to communicate and execute queries on a database (sql database). Establishing a connection with a SQL data base with Node.Js is explained in my previous blog post .

After establishing the connection we just have to execute SQL queries on database and get the results.

Here the table we are changing is "tblstudents" and it has 3 columns "Id", "Name" and "TotalMarks"

Sample Grunt files to manage your tasks with grunt

If you don't have a clear idea about what is Grunt and what is it used for please check my previous blog post about Grunt.

gruntfile.js file for auto execute a nodeJs script after a change in the code

module.exports = function (grunt) {
  grunt.initConfig({
    
    //create task execute
    execute: {
      target: {
        src: ['connectNode.js']
      }
    },
    //watch for changes in connectNode.js file and execute the task "execute"
    watch: {
      scripts: {
        files: ['connectNode.js'],
        tasks: ['execute'],
      },
    }
  });

  //loading necessary node packages
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-execute');
};

Using Grunt in your JavaScript project


What is Grunt and what is it used for, those are the question people have about grunt. Simple answer is Grunt is a task manager written on top of NodeJs and it can be used to manage developers tasks like minification of JavaScript files, Auto reloading the web pages.

Here is a list of tasks that can be managed by Grunt and advantages against using shell scripts for task managing

Node.Js : Connecting with SQL database & retrieve data

First node-mysql package should be installed using npm in your project. (make sure you have installed node.js)

It can be done with code npm install mysql 

Lets get in to code,

  • Add the "mysql" module to application
    var mysql = require("mysql");

Adding a grid of div elements to a web page : CSS

Lets say we have a set of div elements and we want to display them in a grid. Most of people think it is an easy thing. Yes, it is easy, but trust me most of beginners in web developing get this wrong.

Here is an easier way to achieve that.

HTML
<div class="outer_container">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>

directives in angularJs

Names of AngularJs directives starts with "ng-" prefix. Directives are nothing but HTML attributes extended with "ng-" prefix.

There are three main basic directives that every Angular developer must know

  • ng-app 
    Initialize an AngularJs application
  • ng-init 
    Initialize application data
  • ng-model 
    Binds the value of HTML controls such as input, select, textarea to application data.
Here is a simple example of usage of These three directives

Non-blocking implementation with node.js for scalable application

In a normal program normally instructions are executed one by one. Later instructions has to wait till earlier instructions are finished. For this problem we can use threads with some programming languages like java.

following code snippet shows how to code in non-blocking mode to read a file. and you will notice code after reading file will execute while node.Js reading the file. ("task finished" will be printed first)

var fs = require("fs");

fs.readFile('file.txt', function (err, data) {
    if (err) return console.error(err);
    console.log(data.toString());
});

console.log("Task Finished");


How to add an our own directive in angular application.

AngularJs has a useful set of built in directives.They offer a useful set of functionalities for our angular application. What if we want to add a different directive

A new directive can be add using directive() method as same as adding a controller
  • Following code displays how to add a directive and use it our application.
<!DOCTYPE html>
<html>
 <script src="scripts/angular.min.js"></script>
 <body>

  <div ng-app="myApp" my-directive></div>

  <script>
   var app = angular.module("myApp", []);
   app.directive("myDirective", function() {
    return {
        template : "This is a my own directive"
    };
   });
  </script>

 </body>
</html>


Adding model and controller AngularJs application.

Module

A module in angularJs is a collection of services, directives, controllers, filters and configuration information. In simple words it is a container for different parts of an application.

A module can be created in Angular as follows.

var app = angular.module("myApp", []);

angular.module() method takes two parameters.
  • First one is name of the module which is "myApp" in this example.
  • Second one is dependencies for the module.( it will be discussed in future tutorials)

First Step For Angular Js

AngularJs is developed and maintained by Google to allow developers to develop well architectured and easily maintainable web-applications. It is nothing different to plain HTML but simply an extension to HTML with new attributes.

AngularJS is a framework for dynamic web applications and it is client-sided so all these things are happening in browsers and you get the elegance of standalone application. AngularJS makes use of declarative programming for building UI.

Return a HTML response in Node.Js application

This is not a hard thing. An easy one but many of us making problems because of not using this returning a HTML response

When we create a simple server with Node.Js it's code like this

var myServer=http.createServer(function(request,response){ 
 response.writeHead(200,{"Content-Type":"text/plain"}); 
 response.write("Hello World"); //writing a string to response
 response.end(); 
});//create server

Running a simple server using Node.Js : Simplest Node Application

First of all to follow this simple tutorial you should have installed Node.Js .

Lets create a simple HTTP server with Node.Js
  • Open a text editor as your preference
  • Insert this code snippet and save it as hello.js (as a JavaScript File)

    
    var http=require('http'); // add the http module
    
    
    var myServer=http.createServer(function(request,response){
    
     response.writeHead(200,{"Content-Type":"text/plain"});
    
     response.write("Hello World"); //writing a response to String
    
     response.end();
    
    });//create server
    
    myServer.listen(3000); //assign a port to listen
    
    
    
    // Console will print the message
    
    console.log('listening at port 3000');
    
    
    

  • Open a Node.Js command prompt and go to directory where you saved your "hello.js" file
  • Run your simple server with "node hello.js" command.
  • You will see a message "listening on port 3000" if there is nothing wrong
  • Finally open browser and test your HTTP server with entering URL "http://localhost:3000/"

How to use JQuery Form Filters : Examples

JQuery Form filters let you deal with form elements in the DOM easily. For more information and usage about JQuery form filters please refer this post.

This post written by me has more about jquery form filters in details.
In this tutorial we will demonstrate how to select form elements with Jquery filters and apply some CSS changes for it.

Usage of JQuery Form Filters

selecting form elements can be done with JQuery form filters easily. They work like other selectors but starts with colon(:) like regular filters. There are 5 more types of filters and please refer this post about Jquery basic filters for details about other filters.

Here is a list of usage of JQuery Form Filters

JQuery Child Filters

Child filters are one type of filters among 6 different types of filters That provide by JQuery. Please refer this post for details about other JQuery Filters.

With JQuery child filters you can refine by examining the relationship each element has with its parent elements.

Here is the list of usage of child filters.

JQuery Content Filters Visibility Filters

There are 6 different types of filters in JQuery to provide more control over selecting elements. Usage about content filters and visible filters will be discussed in this post.

These filters provide ability to examine the content of selected elements or their visibility property to determine whether they should be included or excluded from the final set.

How to use JQuery attribute filters : Examples

JQuery filters make our work easy by providing a great control over selecting DOM elements.
In this post, examples for using JQuery attribute filters will be demonstrated.
Refer this post for get more details about JQuery attribute filters and their usage.

Lets see some examples of how to select elements with JQuery attribute filters.

Usage of JQuery attribute filters

Filters work with selectors and provide a great control for selecting the elements in DOM. So basically it makes easy our work for selecting elements in DOM.

JQuery filters fall in to six different categories. 
  1. Basic filters
  2. Content filters
  3. Visibility filters
  4. Attribute filters
  5. Child filters
  6. Form filters
In this post is about Attribute filters.

How to use Jquery Basic filters

JQuery filters provide a great control for selecting the elements in DOM as we discussed in earlier post.
For get a better understand about filters read more about JQuery flters from this link.

In this post lets see how to select elements using JQuery filters and applying simple CSS on them

Same HTML file used in previous tutorial for JQuery selectors will be used in this tutorial as well.

Lets get in to work.

here are the JQuery code snippets for filtering DOM elements

  1. Get the first element from a returned set
    $("p:first").css("border","3px solid red");
    This will get the first paragraph element and put a red border around it

  2. Get the last element from a returned set
    $("p:last").css("border","3px solid red");
    This will get the last paragraph element and put a red border around it

  3. Get the odd elements from a returned set
    $("p:odd").css("border","3px solid red");
    This will get the odd paragraph elements and put red borders around them

  4. Get the even elements from a returned set
    $("p:even").css("border","3px solid red");
    This will get the even paragraph elements and put red borders around them

  5. Get the elements past an index from a returned set
    $("p:gt(1)").css("border","3px solid red");
    This will get the paragraph elements indexed as greater than 1 and put red borders around them

  6. Get the element equal to an index from a returned set
    $("p:eq(1)").css("border","3px solid red");
    This will get the paragraph element indexed as equal to 1 and put red borders around it

  7. Get the element not equal to an index from a returned set
    $("p:not(p:eq(1))").css("border","3px solid red");
    This will get all the paragraph elements not indexed as 1 and put red borders around them
Try these simple JQuery selectors and make easy manipulating your DOM.
Please add a comment if you have some thing to add or you are not clear with something.

Basic JQuery filters

Filters work with selectors and provide a great control for selecting the elements in DOM. So basically it makes easy our work for selecting elements in DOM.

JQuery filters fall in to six different categories. 
  1. Basic filters
  2. Content filters
  3. Visibility filters
  4. Attribute filters
  5. Child filters
  6. Form filters
In this post I'm going to discuss about Basic JQuery filters. It provides basic filtering like getting first, last and even and odd numbered items in a returned set.

A List of usage of JQuery filters.


Filter Purpose
:first selects only the first instance of the selector's returned set
:last selects only the last instance of the selector's returned set
:even selects only even numbered elements of the selector's returned set
:odd selects only odd numbered elements of the selector's returned set
:eq(n) filters out elements that are positioned at the given index
:gt(n) include elements that are past the given index
:lt(n) include elements that are before the given index
:header select all header elements (H1, H2, H3 etc)
:animated selects all elements that are currently being animated in some way
:not(selector) includes elements that do not match the given selector

This is just a list of what can be done with JQuery filters.

Please refer this post for practical examples of usage of JQuery basic selectors.

How to use JQuery Scroll() method for detect scroll

It is easy to detect scroll events using JQuery scroll() method.

from this link you can find another way of achieving this task.

Completed project can be download from here.

Here is the JavaScript method for detect scroll of page and do some tasks according to the scrolling position and scrolling movements.


    $(window).scroll(function() {
        if($(window).scrollTop() > 0) {
           $('#maincontent').css("background","gray");
        } else {
            $('#maincontent').css("background","white");
            alert("Now you are in the top");
        }
    });



In this code it will change the color of div that has a ID of "maincontent" when user scrolled and in the bottom of the page.

It will alert a message when user comes to the top of the page.

Scroll detection can be used to enhance user experience with your web page in numerous ways.
feel free to add a comment if you have anything unclear of something to add.

How to detect scroll action using JavaScript

To fire up different actions in a web page when someone scroll on it we need to detect scroll events on the page.

Completed project can be Download from here.
In this tutorial color of a div(div with ID "maincontent") is changed when a user is scrolling the page,

Here is how it can be done.

  1. Add onscroll attribute in the element which you need to detect scroll on.
    ex:<body onscroll="bodyScroll();"></body>

  2. Declare a JavaScript variable to -1. (In this tutorial scrollTimer)

  3. Implement the bodyScroll() function
       function bodyScroll() {        
            $('#maincontent').css('background-color','lightGrey'); 
            
            if (scrollTimer != -1)
                clearTimeout(scrollTimer);

            scrollTimer = window.setTimeout("scrollFinished()", 300);
        }

  4. Implement the scrollFinished() method.
        function scrollFinished() {
           $('#maincontent').css("background","white");
        }

Note: In the project I have added extra reference to bootstrap  for easiness of making the UI.

This post shows hot do this using JQuery scroll() method.

Please add a comment if this was useful to you or you have something to add



Detecting a click on a element in DOM

As web developers some times we need to detect clicks on elements of our DOM to enhance experience with our site. Here is a one simple way we can achieve that.

In this tutorial I have demonstrated how to detect a click on a Image in side a div element.
you can find images used in this tutorial from here.

Here is the HTML for the tutorial

<!DOCTYPE html>

<html>
<head>
    <style>
        .imagegrid{
            border: 3px solid black;
            padding: 10px;
        }
        
        img{
            border: 1px solid red;
            margin: 10px;
        }
    </style>
</head>

<body>
    <h2>Image Grid</h2>
    <div class="imagegrid">
        <img src="Images/facebook.ico">
        <img src="Images/google.ico">
        <img src="Images/Linkedin-icon.png">
        <img src="Images/twitter-icon.png">
    
    </div>  
</body>    
</html>



Java Script code to detect the clicks

var myNode= document.querySelector('.imagegrid');

myNode.addEventListener("click",function(e){

  if(e.target.tagName==="IMG"){
   alert(e.target.src+" clicked");
  } 


},false); 


What happen in the script

  1. Get an element which has "imagegrid" class to myNode variable.
  2. Add an event listener to that myNode element fire up when a click happen.
  3. Alert a message if tagName of a click event (detect by event listener on myNode variable) is equal to "IMG".

In this way you can detect a click on an "img" element as well as other elements in your DOM.
In this tutorial we just alert a message with source of clicked image, but you can do what ever you want after detecting a click on an element like,

  • Taking user to another page
  • Display a larger image of the image
  • Give a hint to the user
This kind of small things give a better experience to the user of your site.


NOTE: CSS parts in the head is added to display limits of images and div with a border

How to use basic JQuery selectors - Part II


This is  the part II of basic JQuery selectors tutorial. You can read Part 1 get example test html file from previous post.
In this post I'm going to talk about retrieve elements with hierarchical relationships using JQuery selectors.

JQuery heirarchical selectors
  • $("p, li.b").css("border","3px solid red");
    This will get the paragraph elements and List elements that has class attribute "b" and putt a red border around them

  • $("ul li.a").css("border","3px solid red");
    this is called descendent selector (for more details). This will get all the list elements has class "a" with in <ul> elements.

  • $("ul+p").css("border","3px solid red");
    This will get the paragraph element next to <ul> element

  • $("#list1 ~ p").css("border","3px solid red");
    This is called sibling selector(for more details). This will get the every paragraph element after element with ID of "list1"
Please feel free to add a comment if you have any problem or some thing to add.

How to use basic JQuery selectors


JQuery selectors are a great way to retrieve content form a page and manipulate the DOM. Its is far more easy to use than using plain browser DOM.

First lets see how to use JQuery selectors to retrieve content from a page and manipulate it.

Examples

<!DOCTYPE html >
<html>
<head>
 <title>Document</title>
 <script type="text/javascript" src="Scripts/jquery-1.11.3.js"></script>
 <script >
  $("document").ready(function(){
   //Your jquery code run when document is ready
  });
 </script>
 <style type="text/css">
  .a { color: Navy; }
  .b { color: Maroon; }
 </style>
</head>
<body>
 <ul id="list1">
 <li class="a">item 1</li>
 <li class="a">item 2</li>
 <li class="b">item 3</li>
 <li class="b">item 4</li>
 </ul>
 <p class="a">This is paragraph 1</p>
 <p>This is paragraph 2</p>
 <p class="b">This is paragraph 3</p>
 <p>This is paragraph 4</p>
</body>
</html> 


This is the code for the html file
In this tutorial we select the elements and put a red border around that element. lets see how to select elements with JQuery. Test following select methods by using codes in place where"Your jquery code run when document is ready" comment appears.
  1. Get elements by type
    $("p").css("border","3px solid red");
    This will get all elements type of  "p" that is paragraph elements and put a red border around it. 

  2. Get elements by ID name
    $("#list1").css("border","3px solid red"); This will get all elements that has ID of "list1" and put a red border around it

  3. Get elements by class attribute
    $(".a").css("border","3px solid red");
    This will get all elements that has class name "a" and put a red border around it.

  4. Get one type type of elements which has a particular class name
    $("p.b").css("border","3px solid red");
    this will get all the paragraph elements which has class attribute of "b".

NOTE:
You need to make sure that you have given correct path to your jquery.js file

Here is a more comprehensive list of JQuery selectors

Selectors and their uses. 
  • tagname - Finds all elements that have type "tagname"
  • #identified - Finds all elements that have ID of "identifier"
  • .className - Finds all elements that have a class attribute of "className"
  • tag.className - Finds all elements that have the type "tag" and a class attribute of "className"
  • tag#id.className -  Finds all elements type of "tag" that has ID of "id" and a class attribute of "className"
  • * - Finds all the elements on the page
For more JQuery Selectors refer this post as well

please add a comment if you have any questions or some thing to add to this post