NodeJs : Modularizing routes with ExpressJs

In a previous post I described how to do routing in a NodeJs app with ExpressJs. When the application gets bigger separate routes from our main code is always a good practice. Lets take a look at, how to separate the routes from our main code.
  1. First step is create a separate folder for routes and lets name it as "routes".
  2. Next create index.js file in "routes" directory
    After this step the project structure will look like this.
    
    |--routes
    |  |-index.js
    |--views
    |  |-default.js 
    |--app.js
    

  3. Export routes in index.js file.
    
    exports.index = function(req,res){
        res.render('default',{title:"Home"});
    }
    

  4. Require the routes folder in app.js file
    
    var routes = require('./routes');
    
  5. Provide methods in index.js file to get method of Express when cofiguring routes
    
    app.get('/',routes.index);

In this way we can modularize our routes in node.js app and we can have a clean and understandable code.

NodeJs : Use the locals object of Express

In previous post we discussed how to pass information to templates using the render() of Express.

In most of websites there is probably some information that you want to pass to all of the templates. With Express we can use the locals object to pass the information that we want any of our templates to access.

Here is how we use the locals object to pass the information

app.locals.siteTitle="My Website";

Information we passed, In this example siteTitle can be accessed like this in any template.

<!DOCTYPE>
<html>
<head>
      
</head>
<body>
   <h1><%=siteTitle %></h1>
  <p>consectetur adipiscing elit. Cras eget dapibus justo. etra justo.</p>  
</body>
</html>

Using EJS as a template engine with ExpressJs

What is a template engine

Template engine is a tool to separate program-logic and presentation into two independent parts.This makes the development of both logic and presentation easier, improves flexibility and eases modification and maintenance.

If it is hard to understand, when we use a template engine we create a page with regular html and we add special tags (<%%>in EJS ) that will contain data or logic.

So when we use express we can use to different template engines.
  1. Jade
  2. EJS
I like EJS because it is very similar to normal HTML

Use EJS with express

First we need to install EJS using npm as a node module to our project.

npm install ejs --save

After installing EJS we need to provide the name of the template engine we are using in this project

var express = require('express');
var app = express();
app.set('view engine','ejs');

Change the default view directory in ExpressJs

When we use ExpressJs for a NodeJs application we need to place our views in a folder named "views". That is the default settings of ExpressJs.

But sometimes we might want to change that location if we use a different structure. So I thought it would be a good idea to write about that configuration though it is a small thing.

This is how we import the express module and create a instance of express.

var express = require('express');
var app = express();

express.set() method can be used to set the path for views folder as follows. "partials" is the name of new views directory.

app.set('views',__dirname+'/partials');

__dirname gives the absolute path of the current directory.

AngularJs : Implement a view with tabs

Tab is a mostly used feature in webpages nowadays. It helps to keep the separation of content and user to view the different content without refreshing page.

This tutorial explains how to make a webpage with tabs using AngularJs as following example
Angular material, an UI Component framework for AngularJs is used in above example. So before go in to that lets make a web page with AngularJs fundamentals and after that we can use the Angular Material for a good look.
Here is the example of tabs using AngularJs fundamentals with the code.

Lets see what we have done

In JavaScript code we have two methods with an array(tabs) and string variable (currentTab), attached to the scope of TabsCtrl controller.

    angular.module('TabsApp', [])
    .controller('TabsCtrl', ['$scope', function ($scope) {
    $scope.currentTab="One";
    
    $scope.tabs = [{
            title: 'One'          
        }, {
            title: 'Two'           
        }, {
            title: 'Three'
        }
     ];

    //$scope.currentTab = $scope.tabs[0].title ;

    $scope.onClickTab = function (tab) {
        $scope.currentTab = tab.title;
    }
    
    $scope.isActiveTab = function(tabTitle) {
        return tabTitle == $scope.currentTab;
    }   
}]);
  1. onClickTab method takes object as input and set title attribute of that object as the currentTab
  2. isActiveTab method takes and string as input. Then return true if it equals to currentTab and return false otherwise
<ul>
            <li ng-repeat="tab in tabs" 
                ng-class="{active:isActiveTab(tab.title)}" 
                ng-click="onClickTab(tab)">{{tab.title}}</li>
        </ul>

Angular directives are used in the HTML code and lets see what do they do.
  1. ng-repeat will go through all the elements in tabs array and repeat <li>elements
  2. ng-class will apply class active if the isActiveTab method returns true
  3. ng-click will execute onClickTab method when clicked on <li>element
<div ng-show="isActiveTab('One')">
</div>
ng-show will display div elements only if isActiveTab method will return true.
 Here is the link for more tab implementations using Angular materials.

Primitive types in JavaScript

In every language there are variable type.In a programming language, if variables are container then data type is the type of container. type of container actually tells that what kind of stuff can be put in it. For example you don't want to put cookies in a bottle similarly you don't want to store an integer value in a variable of data type String

As its name indicates, a data type represents a type of the data which you can process using your computer program. So JavaScript also has 6 Primitive data types other than objects.

Lets Go though each of them.

  1. Undefined
    This represent the lack of existence.(Shouldn't set a variable to this).
  2. Null
    This also represent lack of existence.
  3. Boolean
    This represent a value that is true or false
  4. Number
    This is a floating point number. Normally programming languages have many types of number like int,long,double but JavaScript has only one
  5. String
    This represents a sequence of characters. single quotes ('') or double quotes ("") are used to specify strungs
  6. Symbol
    This type is used in ES6 which is the latest version of JavaScript

What is dynamic typing in JavaScript

When learning a programming language, knowing variable types that programming language supports is an important part. Taking about variable types in JavaScript there are two important thing

  • JavaScript is a dynamically typed language.
  • There are 6 primitive types in JavaScript.

What is dynamic typing

JavaScript is a language that supports dynamic typing. That means, we don't have to tell the JavaScript engine what type of data a variable holds. It figures it out while code is running.

Single variable can hold different types of values at different times of execution of code because it is all figured out during execution.

In static typing we need to specify the what type of data a variable is going to hold and we cant store other types of data in that variable
As an example, in a static typed language like java we can't store a string in a variable that is declared as a boolean.

boolean variable = "hello"; // gives error
But, in a dynamically typed language like JavaScript it can be done without errors.

var box = true;
box = "hiii";
box=3;
//no errors
This is a powerful feature of JavaScript and sometimes it can cause problems as well (If you don't have a proper understanding).

Regular Expressions (Regex) in JavaScript - Part I

Regular Expressions are used to find a specific pattern within a big glob of text. Regular expressions are also known as regex or regexp among developers.

Read this post for how regular expressions are used in JavaScript methods.

In this post series i'm trying to give you an idea about how to create an regex that matches a particular string.

Very Basic Rules 

  1. Every regular expression literal starts and ends with a forward slash ("/").  
  2. Pattern that we are trying to match goes between those slashes.
  3. After end slash "g", "i", "m" characters can be used as flags. Each letter has different purposes.

ES6 Part II : Const and Template literals

As I described in my previous post ES or else ECMAScript is the official name of JavaScript and ES6 that is ECMAScript 6 is the latest version of it.
This is the second of series of posts that explore new features of ES6 so in this post lets look at const keyword and template literals introduced in ES6.

const keyword

In previous versions of JavaScript there was no way to define a constant value. Developers just used only upper case letters to declare a constant variable like,var SEC_KEY="1234567";

 But it could be changed at a latter part of the code. 

var SEC_KEY="1234567";

SEC_KEY="abcdefg";

console.log(SEC_KEY);

ES6 part I : Let key word in ES6

Since this is the first post of a series of posts about ECMAScript 6, I'll explain what is ECMAScript is. ECMAScript is the “proper” name for the language commonly referred to as JavaScript. ECMAScript 6 is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009.

It introduce many new and nice features to make easy programming for programmers.

Let key word

According to description from MDN let keyword allows us to declare variables that are limited in scope to the block, statement, or expression on which it is used.

Use routing in AngularJs

In a Single Page Application (SPA) routing is a important part. AngularJs also provide functions to make easy routing in our SPA. It helps us to,
  • Change the page without refreshing
  • Display different data on different pages
Lets see how to use AngularJs routing in our application to give a better user experience

Our simple app has a menu bar and when different tabs are clicked it should display different pages without refreshing the whole page. It should display list of employees only in home page.

Markup for Main page

<!DOCTYPE html>
<!-- define angular app -->
<html ng-app="myApp">
<head>  
  <!-- CDN for bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

  <!-- CDN for Angulat min and angular-route-->
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
 

Anatomy of call back functions in JavaScript

Call back function is a pattern that heavily used in JavaScript programming. Most of beginners in JavaScript programming have no clear idea about JavaScript programming. Specially Programmers from other programming paradigms except functional programming facing difficulties in adapting this idea.

JavaScript is a functional programming language. So functions are considered as first class objects. There for we can do may things with functions that can't be done in other programming languages. 
Like,
  • Store functions in a variable.
  • Pass functions a arguments to another function. 

What is a Call back function

 A call back function is,
  • passed as an argument to another function.
  • It is invoked after some kind of event.
So basically Call back function is a function (func1) that pass to another function (func2) to be executed after finish the execution of second function (func2).

Nice file upload interface using Jquery

We all know how to upload a file using html form. But I thought to improve that interface a bit using JQuery (Of course I used CSS but i'm writing about JQuery part).

So here is the usual html file uploading interface

I wanted to show a button to choose file and After choosing display a button to upload that file. Chosen file name also displayed in a nice way. As follows


AngularJs : Brief overview of Angular Services

What are Services in AngularJs

According to AngularJs Documentation Services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

It lists two important properties of AngularJs services
  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
There are some useful built in services such as $http and $animateoffered by angular but services can be implemented according to needs in application.

Adding a partial view with JQuery get() method

When we want to add partial views there are a lot of ways to implement. One easy way is using get method provided by JQuery.

Here is a simple script written in JavaScript to change partial views according to user inputs.

             document.getElementById("GetViewsbyPageId").onchange = function () {
                var pageId = $("#GetViewsbyPageId").val();
                if (pageId != 0) {
                    $("#LoadViewsbyPageId").show();
                  //sending a get request
                    $.get('page'+pageId+".html",function (data) {
                        /* data is the pure html returned from get method, load it to your page */
                        $('#LoadViewsbyPageId').html(data);      

                    });
                } else {
                    $("#LoadViewsbyPageId").hide();

                }
             }        

Pop up window with JQuery-UI Dialog() method

Some times it is better to offer popup windows rather than changing the whole page in our web applications. But It is quite difficult to implement it with pure JavaScript, HTML and CSS.

Pop up windows can be easily implemented using JQuery-UI library. Most interesting thing is,
it is..
  • Movable
  • Re-sizable



AngularJs : Adding user Inputs to a HTML table

Some times it would be great if you can update your html view real time with user inputs without sending data to servers. It would increase efficiency of your web application (It could be insecure if used in inappropriate cases).

Here is a simple project for update a html table with user inputs
You need to have a basic understanding about Angular directives, controllers, modules, and scopes to understand this example.

<!DOCTYPE html>
<html  ng-app="app" >
   <head>
      <title>Ajax With Angular</title>
      
      <style>
         table, th , td {
            border: 1px solid grey;            
            border-collapse: collapse;
            padding: 5px;
         }         
          th{
               background: lightgray;
          }
      </style>
      
   </head>

Singleton Pattern in JavaScript

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

In JavaScript this pattern restricts instantiation of an object to a single reference thus reducing its memory footprint and allowing a "delayed" initialization on an as-needed basis. This isn't too common among JavaScript projects.

Here is how a singleton pattern can be implemented with JavaScript

  1. Easiest way is using object literals
    
    var singletonObject ={
        method1:function(){
            
        },
        method2:function(){
        
        }
    }

Tools you must need to know when working with Json

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.It is based on a subset of JavaScript language.(More details)

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. 
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
JSON format is often used for serializing and transmitting structured data over a network connection It can be seen in,
  • web services responses
  • when using Ajax

Mongo-DB Basic Commands

MongoDB is a new type of DBMS.In here things are little different.(More details)

It is non-relational (data not stored in a tabular format)
    • It has collections not tables
    • It has Documents not records
    • A document is a Jason object
So in mongo db  collection ( A table in sql database) is a set of json objects called documents. Database is a set of collections.

Here are some basic commands used to work with mongodb
  • Change the database or create and change
    • use [database name]
      Don't have to worry about the database created or not. just have to use a name if it is not created.
      >>db will return the name of the current database.
      Ex: use people
      People is the name of the database here

AngularJs : AJAX calls with Angular js

AJAX is a necessary part of today web applications. So how to make an AJAX call with AngularJs.

Think we need to make an ajax call to server to get details of a set of student and display when a button clicked.

Here is the complete code for that scenario and I will explain later what happens there.

<!DOCTYPE html>
<html>
   <head>
      <title>Ajax With Angular</title>
      
      <style>
         table, th , td {
            border: 1px solid grey;            
            border-collapse: collapse;
            padding: 5px;
         }         
          th{
               background: lightgray;
          }
      </style>

NodeJs : Handling an AJAX call

Making AJAX calls to server is now a common things in web applications because it provide a better user experience than refreshing a complete page.

Here is a simple HTML page with a text box to search, when user type something in that and press enter an AJAX call will be sent to server

Serving static HTML, JavaScript, CSS files with Express.

How to serve a content according to a requested URL is demonstrated in most for beginners' Express and NodeJs tutorials . But sending just a string is not enough for considerable project. Created  HTML, JavaScript and CSS files should be served when get a user request.

See this HTML page
This was taken from a previous post of How to upload files with express.

<!DOCTYPE html>
<html>
<head>
<title>File Uploading Form</title>      
</head>
<body>
<h3>File Upload:</h3>
Select a file : <br />
<form id = "uploadForm" enctype =  "multipart/form-data" action="/upload" method = "post" >
<input type="file" name="upload_file" />
<input type="submit" value="Upload" name="submit">/form>
    
    <script src="/jquery-1.11.3.js"></script>
    <script src="/upload.js"></script>    
</body>
</html>

Algorithm : Find Number Of Duplicates in Arrays



function sameElementsNaive(a, b) {    
    var count =0;
    for(i=0;i<a.length;i++){
        for(j=0;j<b.length;j++){
            if(a[i]==b[j]){
                count++;
                break;
            }
        }
    }
    return count;
}

Here Two inputs to the function are integer arrays (can be change to other data types as well).

Ex:
sameElementsNaive([1,2,3], [3,4,5]);
this function call should return 1 because only 3 is duplicated in the second array.

Responsive Square grid with HTML and CSS


Adding a  grid  with responsive square to our web page is simple than most of us think.

CSS

.container{    
    width: 100%;
    background: lightgray;    
    display: inline-block;
}

.container div {    
    float:left;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    background-color: #1E1E1E;    
}

Angular Js : Root Scope of an Application

When we are dealing with scopes in an angular Js app it is important to know which scope you are dealing with, at any time. If you have only one scope in your application it is not necessary to be careful about what scope you are using, but for larger application it is not the case, there can be sections in the HTML DOM which can only access certain scopes.

 However all applications have a root scope that is available in the entire application. Here is an simple example on how to access root scope in an Angular Js application.

 Module and Controller for the app

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

app.controller('myCtrl', function($scope, $rootScope) {
    $scope.names = ["DOG", "BIRD", "COW"];
    $rootScope.lastname = "ANIMALS";
});

JQuery : Adding DateTime picker for your form

Adding a date picker to your web form is a handy way instead of just typing dates.

It is simple.

  1. Loading necessary JavaScript and CSS files
    
    <!-- Load jQuery from Google's CDN -->
        <!-- Load jQuery UI CSS  -->
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- Load jQuery JS -->
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <!-- Load jQuery UI Main JS  -->
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    

NodeJs : Uploading files with Express & Multer

Uploading files to server is one of the mostly used features in modern web applications. If you are using node.js "busboy" was the best solution for sometime. But it is somewhat complicated as you can see from examples in it's GitHub homepage.

Multer is the latest best solution for this problem. it is a node.js middle-ware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

Here is an example of how to use Multer to upload files.

Node.Js : Basic routing with Express

Express framework provide different basic ways to configure routing in our web application. Check out my previous post of how to set up a simple HTTP server with Express and Node.Js if you are new to Node and Express.

Handling HTTP requests with different routs  
  1. Handling GET request
    
    //respond to a get request on URL "/"
    app.get('/',function(req,res){
     res.send('Hello Express');
    });
    

    Here URL can be specified as we want instead of "/". 

Encapsulation : private variables in JavaScript

Encapsulation is an one of main concepts in object oriented programming. Encapsulation is the ability that an object has to forbid external access to chosen properties and methods, so that they can only be called by other methods of same object and protect from external unwanted access.

A normal code Snippet

function SecretCode(){
    secretNumber=Math.floor((Math.random() * 10) + 1);     
    
    this.getSecret=function(){
        return secretNumber;
    }
}

var secret1 = new SecretCode();
document.write("value of secret number "+secret1.secretNumber+"<br/>");

document.write("value of secret number : "+secret1.getSecret()+"<br/>");

SecretCode.prototype.getSecretCode= function(){
    return this.secretNumber;    
}

document.write("Secret number is "+secret1.getSecretCode()+"<br/>");

Simple JavaScript : Accessing properties of objects.

There are mainly two ways to access a property in JavaScript.
  • Using dot notation (.)
  • Using square bracket notation ([])
Consider an object like this.

var employee={
    name:"Antony",
    age:26
}

We can access properties of employee object in both ways.
  1. employee.name
  2. employee["name"]
But Consider a object that has non-string property names. Some times we have to use object property names with non-string types.
Ex:
var marks={
    30:"bad",
    70:"good"
}

In here we won't be able to properties with both notation. Only marks["30"] will work.

Creating objects for your design pattern in JavaScript

There are few different ways of creating objects in JavaScript and different ways of using those objects. Most of the beginners in JavaScript are confused with those different ways of handling objects.

Here is a list of few different styles mostly used by developers to create objects.
  1. Object constructor
    
    var person = new Object();
    
    person.name = "Mark",
    person.getName = function(){
      return this.name ; 
    };
    

JavaScript : Inheritance in JavaScript

JavaScript is not a class based language, So it is bit confusing for most of developers familiar with languages like Java or C#.In-order to understand how inheritance work in JavaScript you need to have a good understand about how prototype objects work in JavaScript.

Every object in JavaScript has an internal link to a object. That object is called prototype object. When we trying to access a property from a object JavaScript will first look in that object and if that property is not found next the prototype object will be searched . Refer this link for more details.

So if we want want to inherit properties from another object we can simply point prototype to that object.