Javascript/Ajax/JQuery « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Javascript/Ajax/JQuery ’ Category

Node.js: Unit Testing with Jasmine framework

Posted by on May 14th, 2013

Jasmine is a framework which is used for testing node.js code or javascript code.

Installation

To install the latest official version, use NPM:

npm install jasmine-node -g

Write the specifications for your code in *.js and *.coffee files in the spec/ directory

Execution

After installing the npm package, you can run it with:

jasmine-node spec/filename.js
jasmine-node spec/filename.coffee

For executing multiple test files you can provide multiple filenames as an argument to jasmine-node command.


Key features :

  1. Behavior driven.
  2. It does not require DOM for testing.
  3. Clean and obvious syntax.

Test Cases :

SUITES
Call to a global function ‘describe’ which takes arguments a String and function. The function is a block of code that implements the suite.The String describes the title for the suit.

SPECS
Call to global Jasmine function ‘it’, which like ‘describe’ takes a string and a function. The string is a title for this spec and the function is the spec, or test. A spec contains one or more expectations that examine the state of the code under test,their can be as many ‘it’ functions in describe block.

EXPECTATION
Expectation in jasmine is an assertion which results either true or false. Their can be as many assertions in a spec. Expectations are genrated with the function ‘expect’ which takes an argument which is the actual value. It is chained with a Matcher function, which takes the expected value.

MATCHERS

Each matcher implements the Boolean comparison between actual and expected value. Matchers are used to compare both the values and if all matchers matches or return true only then test is considered as passed else it is considered as failure. Some of the matchers functions are ‘toBe’, ‘toBeTruthy’ etc.
Some examples are as follows:

expect(x).toEqual(y); // compares objects or primitives x and y and passes if they are equivalent
expect(x).toBe(y); // compares objects or primitives x and y and passes if they are the same object
expect(x).toMatch(pattern); //compares x to string or regular expression pattern and passes if they match

beforeEach() and afterEach()

Function ‘beforeEach’ performs task that is to be performed before test begins and ‘afterEach’ performs task that is to be performed after test finished execution.

Sample test

describe("A suite", function() {
var a;

it("A spec", function() {
a = true;

expect(a).toBe(true);
expect(a).not.toBe(false);
});
});

Sahil Chitkara
Software Trainee
Intelligrape Software

Create Basic HTTP Server with Node.js

Posted by on May 10th, 2013

Like other languages(Java, php), we do not need to set up any Apache HTTP server. With Node, things are a bit different, with Node.js, we not only implement our application, we also implement the whole HTTP server. In fact, our web application and its web server are basically the same. Lets create a basic Node HTTP server. First let’s create a main file called server.js in the root directory which we use to start our application, and a module file where our HTTP server code lives, and fill it with the code given below:

var http = require("http");
var requestHandler = function(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
};
var server = http.createServer(requestHandler);
server.listen(9999);
console.log("Server has started.");

Now run the code. To run the server.js script with Node.js type below command:

node server.js

Now open your favorite browser and hit it at http://localhost:9999/. This should display a web page that says “Hello World!”. Well, now lets analyze what’s actually going on here.

1. The first line requires the http module that ships with Node.js and makes it accessible through the variable http.
2. We definded a requestHandler funciton to handle all the requests.
3. We called one of the functions that http module offers: createServer. This function returns an object, which we store in server.
4. This(server) object has a method named listen, and takes a numeric value which indicates the port number our HTTP server is going to listen.

Now lets analyze the, how requestHandler handling the requests. Whenever a request received, requestHandler function gets triggered and two parameters are passed into it, request and response.

1. response.writeHead() send an HTTP status and content-type in the HTTP response header.
2. response.write() send the text “Hello World” in the HTTP response body.
3. response.end() finish response.

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

AngularJS : Getting started with Directives

Posted by on April 25th, 2013

In this post we will go through an important aspect of AngularJS i.e., Directives.

Directives helps us do things in a better and cleaner way. Lets get into the code rather going into theoretical explanations, which will make it more clear what actually directives do.

We have written a simple directive below which shows some HTML when the element being created is encountered.

<html>
<head>
<title>Testing Directive</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
</head>

<body>
<div ng-app="FirstDirective">
    <mytag></mytag>
</div>

<script>

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

myApp.directive('mytag',function(){
    return {
        restrict: "E",
        template: "<strong>This is a great First Directive</strong>",
        replace: true,
    }
})

</script>

</body>
</html>

In the above code, we have “mytag” element which when encountered in HTML renders the corresponding template.  Lets see what the code does,

myApp.directive() is another syntax that we have to remember. The first argument in this is the name of the tag that you want, in our case its “mytag”. Second thing is a factory function which returns an object that defines the directive properties.

In this object we have set “restrict” as E which makes it an Element that can be used like any of HTML tags. The second option “template” defines the HTML template to be loaded and the third option “replace” if set to true replaces the current element with the template.

We will learn more about other options available to us in the next post.

Hope it Helps! Feel free to ask if you have any queries.

AngularJS: Sharing Data between two controllers through a service

Posted by on March 13th, 2013

The topic of this post is quite confusing for many developers as they face problems in identifying the best practice to share data between controllers in AngularJS. Some of the articles out there tell to use $rootScope but that’s not the correct approach to enable this functionality.

A more cleaner and better way of doing so is through a shared service, lets see some code below which will make everything clear.

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

app.factory('MyTestData', function() {
    var testData = {key: 'value',key1:'value1'};
    return {
        showData: function() {
            console.log('Printing Data.....');
            return testData;
        }
    };
});

function First($scope, MyTestData) {
    console.log('First Controller...........');
    console.log(MyTestData.showData());
}

function Second($scope, MyTestData) {
    console.log('Second Controller..........');
    console.log(MyTestData.showData());
}

 

<!--html code-->
<div ng-controller="First">

</div>
<div ng-controller="Second">

</div>

When you run the above code, it will console the value of testData in the browser from both the controllers. In the above code we have used .factory which is another way of defining a service, you can find more information regarding that in angular docs. I hope it helps, feel free to ask if you have any queries.

Difference Between ‘null’ and ‘undefined’ in JavaScript

Posted by on March 1st, 2013

Most people using JavaScript misunderstand the difference between ‘null’ and ‘undefined’. An unclear distinction between these two entities can lead to grave issues when using ‘null’ and ‘undefined’ in test cases.

A variable is said to be ‘undefined’ if it has been declared, but no value has been given to it. Contrary to this, ‘null’ is a value that can be assigned to a variable and represents ‘no value’. Therefore, ‘undefined’ is a variable type whereas ‘null’ is an object value.

Null’ in JavaScript

‘Null’ is a keyword in JavaScript that signifies ‘no value’ or nonexistence of any value. If you wish to shred a variable off its assigned value, you can simply assign ‘null’ to it. Besides this, like any other object, it is never implicitly assigned to a variable by JavaScript.
An example of explicit null assignment is –

var some_item= null;
console.log(some_item)

Upon execution, the code will print null.

Undefined’ in JavaScript

‘Undefined’ is a global variable that JavaScript creates at run time. This global variable is assigned to an object in one of the following cases –

1. Declared but not defined –
JavaScript assigns ‘undefined’ to any object that has been declared but not initialized or defined. In other words, in a case where no value has been explicitly assigned to the variable, JavaScript calls it ‘undefined’.

2. Array index or object property that does not exist.

3. A function parameter that has not been supplied.

4. The return value of functions that have to but don’t return a value.

An illustration of this assignment is shown in the following –

var item;
console.log(item)

Upon execution, the code will print undefined.

Difference in Type –  

‘Null’ is an object with a valid value, no properties, is non-mutable, and only a single instance of the same exists in the system at all times. In case you wish to verify the object nature of ‘null’, you can use the ‘typeof’ operator. The use of the same will give the output as ‘object’. However, if you use the ‘typeof’ operator on an object that belongs to one of the points mentioned in the ‘undefined’ list, you will get the object type as ‘undefined’.

Conversion to Primitive Types - 

A major difference between ‘null’ and ‘undefined’ is in the way they are converted to primitive types. When you perform arithmetic conversion on ‘null’, the value determined is 0. This conversion can be verified using the following code snippet.

var v1= 5+ null;
console.log(v1)

Upon execution, this output of this code will print 5.
However, ‘undefined’ does not carry out any such conversion. If you try to add ‘undefined’ to a numeral, you will get NaN or Not-a-Number. The following code snippet illustrates this facet of ‘undefined’.

var v2= 5+ undefined;
console.log(v2)

Upon execution, the code will print NaN.

Hope this will help. :-)
Sakshi Tyagi
sakshi@intelligrape.com

Clustering in Node.js

Posted by on February 25th, 2013

Node.js is single threaded so it runs one process on a single CPU, as the power of Node.js is its performance and speed it doesn’t seem good to use only one CPU in a multi-core system. For utilizing all the CPUs, Node.js allows us to create a network of processes that all shares the same port.

Create a file named clusterExample.js

var cluster = require('cluster'); //use the cluster module
var http = require('http')
var noOfCPUs = require('os').cpus().length(); //count the no of CPUs available

if (cluster.isMaster) { //Check if the cluster is master or worker process
  for (var i = 0; i < noOfCPUs; i++) {
    cluster.fork() //creates a worker process
  }

  //give message on console when worker process starts listening
  cluster.on('listening', function (worker, address) {
    console.log("A new worker process with #" + worker.id + " is now listening to " + ":" + address.port);
  });

  //give message on console and create a new worker porcess when a worker process dies
  cluster.on('exit', function (worker, code, signal) {
    console.log("worker process with #" + worker.process.pid + "died");
    cluster.fork(); //create the new worker process
  });
} else {
  http.createServer(function (req, res) {
    res.writeHead(200);
    res.end("Cluster Example\n");
  }).listen(9090);
}

Now run the clusterExample.js

node clusterExample.js

Output:

A new worker process with #1 is now listening to :9090
A new worker process with #2 is now listening to :9090
A new worker process with #3 is now listening to :9090
A new worker process with #4 is now listening to :9090

Shreyance Jain
shreyance@intelligrape.com

How to implement Inheritance in js2

Posted by on February 18th, 2013

We are assuming that you have installed js2 in your system, in case if you have not installed js2, first install js2.

First of all create a InheritanceTest.js2 file in scr directory with the content given below:

class Person { // Parent class
    var firstName;
    var lastName;

    function initialize(firstName, lastName) { // Constructor
        this.firstName = firstName;
        this.lastName = lastName;
    }

    function toString() {
        return this.firstName + ' ' + this.lastName;
    }
}

class Employee extends Person { // Child class
    var companyName;

    function initialize(firstName, lastName, companyName) { // Constructor
        this.$super(firstName, lastName);
        this.companyName = companyName;
    }

    function toString() {
        return this.$super() + ', ' + this.companyName;
    }
}

To compile js2 file into js file in lib directory run the command given below:

js2-node compile -f=node ./src ./lib

Now create a js script named as inheritance.js in scr directory with following content:

var Person = require('../lib/InheritanceTest').Person;
var Employee = require('../lib/InheritanceTest').Employee;

var person = new Person("Amit", "Thakkar");
console.log(person.toString())
var employee = new Employee("Amit", "Kumar", "Intelligrape");
console.log(employee.toString())

Now run inheritance.js file with the command given below:

node src/hello.js
// Output
Amit Thakkar
Amit Kumar, Intelligrape

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

Getting started with js2

Posted by on February 16th, 2013

We are assuming that you have installed node.js in your system, in case if you have not installed node.js, first install node.js.
To install js2 run the command given below:

npm install js2

Let’s create a simple Hello World project, but first let’s create a project directory structure:

mkdir helloWorldJs2
cd helloWorldJs2
mkdir scr lib

Now create a HelloWorld.js2 file in scr directory with the content given below:

class HelloWorld {
  function sayHelloWorld() {
    console.log("Hello World");
  }
}

To compile js2 file into js file in lib directory run the command given below:

js2-node compile -f=node ./src ./lib

Above command will compile HellowWorld.js2 file and will generate HelloWorld.js file in lib directory. Now create a js script named as hello.js in scr directory with following content:

var HelloWorld = require('../lib/HelloWorld').HelloWorld;
var helloWorld = new HelloWorld();
helloWorld.sayHelloWorld();

Now run hello.js file with the command given below, And you will get Hello World printed at console.

node src/hello.js

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

Node.js: Getting started with Express.js and MongoDB

Posted by on February 8th, 2013

In my previous post, i explained how to get started with node.js and executing your first script with node. Now in this tutorial we will go a step ahead and learn using Expressjs and MongoDB.

For people who are new, Express is a web application framework for node which provides nice set of features that can be used to build single-page as well as multi-page web apps and MongoDB is high performance non-relational database. You can know more about both of these on their respective websites.

Installation Part:

Run this command to install the express module globally for developing apps.

$ npm install -g express

Now go into your project directory and run the following commands in series:

$ express --sessions --css stylus --ejs myapp    //creating app with express
$ cd myapp && npm install    //installing dependencies

Now you are done with initializing your first express app, we will come back to it later on. We now move to MongoDB, goto their website and download the installation .deb file for linux systems or you can run the following command in console:

sudo apt-get install mongodb-10gen

After the installation is done, enter mongo in console and it should put you in the mongo console where you can execute various commands. Next we install a node module named mongoose, it is a good mongodb object modelling module for node.js so we will be using this, to do that goto your myapp directory and run the following command in console:

$ npm install mongoose

That ends the installation part, moving on to coding we need to first create views which is basically html pages coded in .ejs (embedded javascript) format. If you goto the views directory in the app, you will find a default index.ejs file which we will be editing for our use later on. The basic thing we will be doing in this app is to save records in database through a form and and display it on the front end in another view.

For all db processing create a new db.js file in a new model folder, this is where all our db specific methods would be defined.

 var mongoose = require('mongoose');
var demoSchema = new mongoose.Schema({
    name:String
});
var hello = mongoose.model('hello', demoSchema);
mongoose.connect('localhost', 'test');

In the same file, make two new functions as follows:

exports.saveUser = function (req, res) {
    this.user = req.body.user;
    new hello({name:this.user}).save(function (err, login) {
        if (err) {
            return console.log('error');
        }
        else {
            console.log('Saved');
            res.render('index', {title:'Welcome', message:'User Added!'});
        }
    });
}

 

exports.showUser = function (req, res) {
    hello.find({},function (err, results) {
        res.render('showUser', { 'title':'Results', 'results':results, message:'' });
    });
};

Add the following lines to your app.js file:

var db = require('./model/db');
app.post('/saveUser', db.saveUser);
app.get('/showuser', db.showUser);

Now open the index.js file which will be in the routes directory of your project and replace its content with following code:

exports.index = function(req, res){
  <code>res.render(</code><code>'index'</code><code>, {title:</code><code>'Welcome to my App'</code><code>, message:</code><code>''</code><code>});</code>
};

Now open the index.ejs file and add the following content, (you can replace all of the previous content or just add to it).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><%= title %></title>
<meta name="description" content="First Express App- by Suroor Wijdan">
<link href="/stylesheets/style.css" rel="stylesheet">
</style>
</head>
<body>
<div>
<%=message%>

<form action="saveUser" method="POST">
       <input type = "text" name = "user" >
       <input type = "submit" value = "Save User">
</form>
</body>
</html>

Make another showUser.ejs file in views with following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><%= title %></title>
<meta name="description" content="First Express App- by Suroor Wijdan">
<link href="/stylesheets/style.css" rel="stylesheet">
</style>
</head>
<body>

<table class="table table-striped table-bordered table-condensed">
                    <thead>
                        <tr>
                            <th>Results</th>
                        </tr>
                    </thead>
                    <tbody>
                        <% results.forEach(function(element) { %>
                        <tr>
                            <td><%=element.name%></td>
                        </tr>
                        <% }) %>
                    </tbody>
                </table>
</body>
</html>

We are done with creating our first express app, you can access the showUser page at your localhost:3000/showUser. Let me know if you have any queries related to this tutorial in comments below.

Getting started with node.js on Linux

Posted by on February 1st, 2013

In this tutorial i will walk you through the installation of node.js on your Linux system and executing your first script with node. To get started goto the official node.js website and download the Linux Binaries file (as shown in the screenshot below) according the bit version of your system.

nodejs linux download

Save the downloaded file in a specific directory and open Terminal, now execute the following command to extract the contents of the file which must be having the .tar.gz extension.

sudo tar -zxvf node-v0.8.18.tar.gz

Once the file has been extracted you will see that a new directory has been created with the name node-v0.8.14-linux-x64. We are halfway in setting up node, now we need to export the environment variable for the node’s /bin directory so that we can access its console from anywhere. To do so, goto your home directory and open .bashrc file and scroll till the end. If you have java installed on your system then you will probably be having a environment variable already set for it, now you just need to add the path for node below it as shown in the screenshot below.

nodejs environment path

Now your done with the node.js setup. Type node in your console and it should put you in the node console.

Executing first script with node.js:

In the second part of this tutorial we will create a simple file with one line that will print Hello World when executed with node. Firstly create a file named firstDemo.js with a single line given below:

console.log("Hello World");

Now goto terminal and type the command shown in the screenshot to execute the firstDemo.js file, be sure that you are in the directory where you create the file.
nodejs-demo
Hope it helps :)