Search This Blog

2015-11-16

Node.js - Event Loop and Event Emitter

Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur.

Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events.

EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

Below is an example :

Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.
Step 3: index.js will be as below

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
// Create an event handler as follows
var connectHandler = function connected() {
   console.log('connection succesful.');
 
   // Fire the data_received event
   eventEmitter.emit('data_received');
}
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);

// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
   console.log('data received succesfully.');
});
// Fire the connection event
var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'data_received');
console.log(eventListeners + " Listner(s) listening to data_received event");
console.log("Listner Count Ended...............");
eventEmitter.emit('connection');
console.log("Connection Event Ended...............");
eventEmitter.emit('data_received');
console.log("data_received Event Ended...............");
eventEmitter.removeAllListeners();
eventEmitter.emit('connection');
console.log("Program Ended...............");
Step 5: Run the application by 'node index.js' and see the responses in console.



 
 

2015-11-14

Angular JS Routing

The routing functionality added by this step is provided by angular in the ngRoute module, which is distributed separately from the core Angular framework.

Step 1) Finish Serving a HTML file from Node JS

    Step 2) Create folder and files as below
Step 3)about.html

<div class="jumbotron text-center">
    <h1>About Page</h1>

    <p>{{ message }}</p>
</div>

Step 4) contact.html
<div class="jumbotron text-center">
    <h1>Contact Page</h1>

    <p>{{ message }}</p>
</div>

Step 5)error.html
<div class="jumbotron text-center">
    <h1>Error Page</h1>

    <p>{{ message }}</p>
</div>

Step 6)home.html

<div class="jumbotron text-center">
    <h1>Home Page</h1>

    <p>{{ message }}</p>
</div>

Step 7)routing.html

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
   
    <!-- load bootstrap and fontawesome via CDN -->
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

    <!-- load angular and angular route via CDN -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
    
    
    <script src="routing.js"></script>
</head>
<body ng-app="myApp" ng-controller="mainController">
    <!-- HEADER AND NAVBAR -->
    <header>
        <nav class="navbar navbar-default">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/">Angular Routing Example</a>
                </div>

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#!/"><i class="fa fa-home"></i> Home</a></li>
                    <li><a href="#!/about"><i class="fa fa-shield"></i> About</a></li>
                    <li><a href="#!/contact/07448587873"><i class="fa fa-comment"></i> Contact</a></li>
                </ul>
            </div>
        </nav>
    </header>

    <!-- MAIN CONTENT AND INJECTED VIEWS -->
    <div id="main">
        {{ message }}

        <div ng-view></div>
        <!-- angular templating -->
        <!-- this is where content will be injected -->

    </div>

</body>
</html>


Step 8)routing.js

// create the module and name it myApp
// also include ngRoute for all our routing needs
var myApp = angular.module('myApp', ['ngRoute']);

// configure our routes
myApp.config(function ($routeProvider, $locationProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl: 'pages/home.html',
            controller: 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl: 'pages/about.html',
            controller: 'aboutController'
        })

        // route for the contact page
        .when('/contact/:id', {
            templateUrl: 'pages/contact.html',
            controller: 'contactController'
        })
        .otherwise({   // This is when any route not matched
            templateUrl: 'pages/error.html',
            controller: 'errorController'
        })
    $locationProvider.html5Mode(false).hashPrefix('!'); // This is for Hashbang Mode
});

// create the controller and inject Angular's $scope
myApp.controller('mainController', function ($scope) {
    // create a message to display in our view
    $scope.message = 'Everyone come and see how good I look!';
});

myApp.controller('aboutController', function ($scope) {
    $scope.message = 'Look! I am an about page.';
});

myApp.controller('contactController', function ($scope, $routeParams) {
    $scope.message = 'Contact us! JK. This is just a demo.'  +$routeParams.id;
});

myApp.controller('errorController', function ($scope) {
    $scope.message = '404 : Not Found';
});


Step 9)run your code using 'node index.js' and Open your browser and try browsing your routing.html file (http://localhost:7879/routing.html)



2015-11-01

AngularJS

AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

It could be downloaded from https://angularjs.org/

Sample Application:

1)Create 3 file index.html,app.js and appcontroller.js

2)index.html:
<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src="app.js"></script>
    <script src="appcontroller.js"></script>
</head>
<body>
    <form ng-app="myApp" ng-controller="customersCtrl" name="myForm" novalidate>
<!-- ng-app Defines the root element of an application.  -->
        <ul>
            <li ng-repeat="x in names| orderBy : 'Country'"> <!-- ng-repeat : Defines a template for each data in a collection.  -->
               <!-- AngularJS Filters:
                currency- Format a number to a currency format.
                filter- Select a subset of items from an array.
                lowercase- Format a string to lower case.
                orderBy- Orders an array by an expression.
                uppercase- Format a string to upper case.  -->
                <span ng-show="x.Country != 'France'"> <!-- ng-show : Shows or hides HTML elements.  -->

                    {{ x.Name +' , '+ x.City +', ' + x.Country|uppercase }}
                <input type="text" ng-model="x.City"> <!-- ng-model: Binds the value of HTML controls to application data.  -->
               
                    <button ng-click="getCity(x.City)">Click Me</button>
                    <!-- AngularJS support the following events:
                    •ng-click
                    •ng-dbl-click
                    •ng-mousedown
                    •ng-mouseenter
                    •ng-mouseleave
                    •ng-mousemove
                    •ng-keydown
                    •ng-keyup
                    •ng-keypress
                    •ng-change -->


                </span>
            </li>
        </ul>
        <p>Email:<br>
          <input type="email" name="email" ng-model="email" id="myemail" required>
          <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
          <span ng-show="myForm.email.$error.required">Email is required.</span>
          <span ng-show="myForm.email.$error.email">Invalid email address.</span>
          </span>
        </p>
        <!-- Validation
        $dirty- The user has interacted with the field.
        $valid- The field content is valid.
        $invalid- The field content is invalid.
        $pristine- User has not interacted with the field yet.  -->

     
    </form>

</body>
</html>


2)app.js

var app = angular.module('myApp', []); 
// angular.module() -Creates, registers, or retrieves an AngularJS module

3)appcontroller.js

app.controller('customersCtrl', function ($scope, $http) {
   
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function (response) { $scope.names = response.records; });
   
    $scope.getCity = function (input) {
        alert(input);
    }
});