Creating App with Express.js

Pre-Requisite

  • NodeJS
  • MongoDB

Initialize App

npm init

Installing NodeJS Modules

npm install --save express
npm install --save mongoose
npm install --save node-restful
npm install --save method-override
npm install --save body-parser
npm install --save lodash

/index.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');

// Create the application.
var app = express();

// Add Middleware necessary for REST API's
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));

// CORS Support
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// Connect to MongoDB
mongoose.connect('mongodb://localhost/meanapp');
mongoose.connection.once('open', function() {

  // Load the models.
  app.models = require('./models/index');

  // Load the routes.
  var routes = require('./routes');
  _.each(routes, function(controller, route) {
    app.use(route, controller(app, route));
  });

  console.log('Listening on port 3000...');
  app.listen(3000);
});

/models/Movie.js

var mongoose = require('mongoose');

// Create the MovieSchema.
var MovieSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  url: {
    type: String,
    required: true
  }
});

// Export the model schema.
module.exports = MovieSchema;

/models/index.js

module.exports = {
  movie: require('./Movie')
};

/controllers/MovieController.js

var restful = require('node-restful');
module.exports = function(app, route) {

  // Setup the controller for REST.
  var rest = restful.model(
    'movie',
    app.models.movie
  ).methods(['get', 'put', 'post', 'delete']);

  // Register this endpoint with the application.
  rest.register(app, route);

  // Return middleware.
  return function(req, res, next) {
    next();
  };
};

/routes.js

module.exports = {
  '/movie': require('./controllers/MovieController')
};

Running the App

node index.js

 

In browser type http://localhost:3000

 

ECMAScript 6: Get Set Go

ECMAScript 6 is a significant update to the language. Implementation of these features in major JavaScript engines are in progress.

ES6 includes the following new features:

1. Arrows

// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var pairs = evens.map(v => ({even: v, odd: v + 1}));

// Statement bodies
nums.forEach(v => {
  if (v % 5 === 0)
    fives.push(v);
});

// Lexical this
var bob = {
  _name: "Bob",
  _friends: [],
  printFriends() {
    this._friends.forEach(f =>
      console.log(this._name + " knows " + f));
  }
}

2. Classes

class SkinnedMesh extends THREE.Mesh {
  constructor(geometry, materials) {
    super(geometry, materials);

    this.idMatrix = SkinnedMesh.defaultMatrix();
    this.bones = [];
    this.boneMatrices = [];
    //...
  }
  update(camera) {
    //...
    super.update();
  }
  get boneCount() {
    return this.bones.length;
  }
  set matrixType(matrixType) {
    this.idMatrix = SkinnedMesh[matrixType]();
  }
  static defaultMatrix() {
    return new THREE.Matrix4();
  }
}

3. Enhanced Object Literals

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

4. Template Strings

// Basic literal string creation
`In JavaScript '\n' is a line-feed.`

// Multiline strings
`In JavaScript this is
 not legal.`

// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`http://foo.org/bar?a=${a}&b=${b}
     Content-Type: application/json
     X-Credentials: ${credentials}
     { "foo": ${foo},
       "bar": ${bar}}`(myOnReadyStateChangeHandler);

5. Destructuring

// list matching
var [a, , b] = [1,2,3];

// object matching
var { op: a, lhs: { op: b }, rhs: c }
       = getASTNode()

// object matching shorthand
// binds `op`, `lhs` and `rhs` in scope
var {op, lhs, rhs} = getASTNode()

// Can be used in parameter position
function g({name: x}) {
  console.log(x);
}
g({name: 5})

// Fail-soft destructuring
var [a] = [];
a === undefined;

// Fail-soft destructuring with defaults
var [a = 1] = [];
a === 1;

6. Default + Rest + Spread

function f(x, y=12) {
  // y is 12 if not passed (or passed as undefined)
  return x + y;
}
f(3) == 15
function f(x, ...y) {
  // y is an Array
  return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
  return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6

7. Let + Const

function f() {
  {
    let x;
    {
      // okay, block scoped name
      const x = "sneaky";
      // error, const
      x = "foo";
    }
    // error, already declared in block
    let x = "inner";
  }
}

8. Iterators + For..of

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
        return { done: false, value: cur }
      }
    }
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}

9. Generators

var fibonacci = {
  [Symbol.iterator]: function*() {
    var pre = 0, cur = 1;
    for (;;) {
      var temp = pre;
      pre = cur;
      cur += temp;
      yield cur;
    }
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}

10. Unicode

// same as ES5.1
"𠮷".length == 2

// new RegExp behaviour, opt-in ‘u’
"𠮷".match(/./u)[0].length == 2

// new form
"\u{20BB7}"=="𠮷"=="\uD842\uDFB7"

// new String ops
"𠮷".codePointAt(0) == 0x20BB7

// for-of iterates code points
for(var c of "𠮷") {
  console.log(c);
}

11. Modules

// lib/math.js
export function sum(x, y) {
  return x + y;
}
export var pi = 3.141593;
// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));

12. Module Loaders

// Dynamic loading – ‘System’ is default loader
System.import('lib/math').then(function(m) {
  alert("2π = " + m.sum(m.pi, m.pi));
});

// Create execution sandboxes – new Loaders
var loader = new Loader({
  global: fixup(window) // replace ‘console.log’
});
loader.eval("console.log('hello world!');");

// Directly manipulate module cache
System.get('jquery');
System.set('jquery', Module({$: $})); // WARNING: not yet finalized

13. Map + Set + Weakmap + Weakset

// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;

// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;

// Weak Maps
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined

// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set

14. Proxies

// Proxying a normal object
var target = {};
var handler = {
  get: function (receiver, name) {
    return `Hello, ${name}!`;
  }
};

var p = new Proxy(target, handler);
p.world === 'Hello, world!';
// Proxying a function object
var target = function () { return 'I am the target'; };
var handler = {
  apply: function (receiver, ...args) {
    return 'I am the proxy';
  }
};

var p = new Proxy(target, handler);
p() === 'I am the proxy';

15. Symbols

var MyClass = (function() {

  // module scoped symbol
  var key = Symbol("key");

  function MyClass(privateData) {
    this[key] = privateData;
  }

  MyClass.prototype = {
    doStuff: function() {
      ... this[key] ...
    }
  };

  return MyClass;
})();

var c = new MyClass("hello")
c["key"] === undefined

16. Subclassable Built-ins

// Pseudo-code of Array
class Array {
    constructor(...args) { /* ... */ }
    static [Symbol.create]() {
        // Install special [[DefineOwnProperty]]
        // to magically update 'length'
    }
}

// User code of Array subclass
class MyArray extends Array {
    constructor(...args) { super(...args); }
}

// Two-phase 'new':
// 1) Call @@create to allocate object
// 2) Invoke constructor on new instance
var arr = new MyArray();
arr[1] = 12;
arr.length == 2

17. Promises

function timeout(duration = 0) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, duration);
    })
}

var p = timeout(1000).then(() => {
    return timeout(2000);
}).then(() => {
    throw new Error("hmm");
}).catch(err => {
    return Promise.all([timeout(100), timeout(200)]);
})

18. Math + Number + String + Array + Object Apis

Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false

Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2

"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"

Array.from(document.querySelectorAll('*')) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
[0, 0, 0].fill(7, 1) // [0,7,7]
[1, 2, 3].find(x => x == 3) // 3
[1, 2, 3].findIndex(x => x == 2) // 1
[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"

Object.assign(Point, { origin: new Point(0,0) })

19. Binary And Octal Literals

0b111110111 === 503 // true
0o767 === 503 // true

20. Tail Calls

function factorial(n, acc = 1) {
    'use strict';
    if (n <= 1) return acc;
    return factorial(n - 1, n * acc);
}

// Stack overflow in most implementations today,
// but safe on arbitrary inputs in ES6
factorial(100000)

Grunt: Get Set Go!

Grunt is a javascript task runner that provides automation for repetitive tasks like minification, compilation, unit testing, linting, etc.

Setup

Install Node.js from http://nodejs.org/ as grunt runs on top of it.

Run following command to install grunt CLI. It allows to run grunt command from any directory.

npm install -g grunt-cli

Now create package.json & Gruntfile.js file

Creating package.json file

This file stores project development dependencies. This is placed in root of project folder. Run following command to create package.json file with basic structure.

npm init

Installing dependencies: This will install all dependencies of devDependencies object.

npm install

Installing Grunt: This will install grunt and save in devDependencies object.

npm install grunt --save-dev

This will store the grunt plugins in node_modules directory in root of project folder.

Like this other grunt plugins can be installed from http://gruntjs.com/plugins. Following are some useful plugins used commonly:

// For javascript:
npm install grunt-contrib-jshint --save-dev  // Validate files with JSHint
npm install grunt-contrib-uglify --save-dev  // Minify files with UglifyJS

// For css:
npm install grunt-contrib-sass --save-dev    // Compile Sass to CSS
// or
npm install grunt-contrib-compass --save-dev // Compile Sass to CSS using Compass

// For files & folders:
npm install grunt-contrib-clean --save-dev   // Clean files and folders
npm install grunt-contrib-watch --save-dev   // Run predefined tasks whenever watched file patterns are added, changed or deleted

Creating Gruntfile.js file

This file defines and configures the tasks to be run by Grunt. This is placed in root of project folder. Create Gruntfile.js file and write following code:

/* This is wrapper function */
module.exports = function(grunt){

  /* 1. Project configuration */
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    /* 2. Configure tasks */

    jshint: {
      all: {  // Custom name to call from other tasks
        src: ['Gruntfile.js', 'assets/js/*.js']
      },
      lib: {  // Custom name to call from other tasks
        src: ['assets/js/lib/*.js']
      },
      module: {  // Custom name to call from other tasks
        src: ['assets/js/module/*.js']
      }
    },

    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */'
      },
      lib :{  // Custom name to call from other tasks
        src: ['assets/js/lib/*.js'],
        dest: 'assets/min/js/lib.min.js'
      },
      module :{  // Custom name to call from other tasks
        src: ['assets/js/module/*.js'],
        dest: 'assets/min/js/main.min.js'
      }
    },

    // IMPORTANT: This task require Ruby & Sass installed
    sass: {
      options: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */'
      },
      build: {  // Custom name to call from other tasks
        options: {
          style: 'compressed'
        },
        files: {
          'assets/min/css/common.css': 'assets/sass/common.scss',
          'assets/min/css/style.css': 'assets/sass/style.scss'
        }
      }
    },

    clean: {
      all: {  // Custom name to call from other tasks
        src: ['assets/min/*']
      },
      lib: {  // Custom name to call from other tasks
        src: ['assets/min/js/lib/*']
      },
      module: {  // Custom name to call from other tasks
        src: ['assets/min/js/module/*']
      },
      css: {  // Custom name to call from other tasks
        src: ['assets/min/css/*']
      }
    },

    watch: {
      js: {  // Custom name to call from other tasks
        files: ['assets/js/module/*.js'],
        tasks: ['jshint:module', 'clean:module', 'uglify:module'] // Order of task is important
      },
      css: {  // Custom name to call from other tasks
        files: ['assets/sass/*.sass'],
        tasks: ['clean:css', 'sass'] // Order of task is important
      }
    }
  });

  /* 3. Load grunt plugins for the configured tasks */
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-watch');

  /* 4. Register the default tasks that will run when grunt command is executed */
  grunt.registerTask('default', ['jshint:all', 'clean:all', 'uglify', 'sass', 'watch']); // Order of task is important
};

Finally run grunt command

grunt

jQuery: Handling multiple ajax request simultaneously

Situation:
On the page we have to show/handle data from different request asynchronously like IP address coming from http://ip.jsontest.com and Date & time coming from http://date.jsontest.com. How we will hit multiple ajax request in parallel and after their successful hit how we will show/handle their response?

Solution:
jQuery 1.5 introduces Deferred Object to handle asynchronous operations. Deferred object is chainable and it has its own methods. Deferred objects are used in conjunction with the promise concept of $.when() to wait for all of the Deferred object’s requests to complete executing (i.e. for all of the promises to be fulfilled)

With $.when() either $.then() or $.done() method can be used to handle resolved request(s).

Our situation approach with $.when() & $.then()

var result = {};

$.when(
    $.ajax({
        url: 'http://ip.jsontest.com',
        success: function(data){
            result.ipAddress = data;
        }
    }),
    $.ajax({
        url: 'http://date.jsontest.com',
        success: function(data){
            result.dateTime = data;
        }
    })
).then(function(){
    console.log(result);
}).fail(function(){
    console.log('Unable to perform operation!');
});

Our situation approach with $.when() & $.done()

var result = {};

$.when(
    $.ajax({
        url: 'http://ip.jsontest.com'
    }),
    $.ajax({
        url: 'http://date.jsontest.com'
    })
).done(function(data1, data2){
    result.ipAddress = data1[0];
    result.dateTime = data2[0];
    console.log(result);
}).fail(function(){
    console.log('Unable to perform operation!');
});