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).