• CEO
  • Android Apps
  • Desktop Apps
  • Our History

Welcome to Tutorials

Overview

I'm a full stack web developer with more than 6 years of professional experience in both front end and back end development. I've worked with NodeJS, AngularJS, Java 2EE, proprietary web servers, and more. I'm well-versed in all areas of front-end development. I strive to learn new techniques and technologies regularly.
How to Create NodeJS app with MySQL Example

In this tutorial, I will show how to go from nothing installed, to a fully-functioning Node.js web app, using the Express framework, that reads from and writes to a MySQL database. This will be a great start, and if you’re unfamiliar with some of these technologies, now would be an excellent time to start learning them. I am going to show how to get a webserver running with Express, and how to use app.get and app.post to communicate with both the server and the database. Here I am going to share my experiences of developing for fun.

In this tutorial, I will show how to go from nothing installed, to a fully-functioning Node.js web app, using the Express framework, that reads from and writes to a MySQL database. This will be a great start, and if you're unfamiliar with some of these technologies, now would be an excellent time to start learning them. I am going to show how to get a webserver running with Express, and how to use app.get and app.post to communicate with both the server and the database.

In this example the service is implemented using the principles of the REpresentational State Transfer (REST) architectural style. It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used. REST is an architecture style for designing networked applications.

For the database I am using a Library Management database as an example. I will show how to query from the app to the database in order to add, remove, update and delete items from the tables. I will use MySQL for the database server but this example can be applied to Oracle database as well.

Here's the deal: I'm going to show you how to get all of this stuff set up. I'll be assuming that you're familiar with MySQL and know how to install its workbench and server. For more details you can look at here.

Let's start with importing the library model to MySQL and populate it with some data. You can get the files from GitHub.

Setup the database

Our library database has following tables:

  • Book,
  • Author,
  • Publisher,
  • Borrower,
  • Loan,
  • Library Branches, and
  • Book Copies

Here is the Enhanced Entity Relationship (EER) diagram for our database.

Here is the Enhanced Entity Relationship (EER) for our library database

In following snapshots I will show you how to open the library model and creating the tables with in the MySQL workbench.

First go to File->Open Module... (press Ctrl + O for shortcut)

Open Model

Go to the location where you have saved the library.mwb file, Select the file and click Open.

Open LibraryApp

There might be an Alert regarding changing the indexes. Please click Rename.

Ignore Message

The EER diagram for the database will be open. This diagram shows the relationships between tables.

EER Opened

Now we need to create the tables from EER diagram. Go to Database option and click Forward Engineer...

Forward Engineer

In this step parameter setting wizard will open.  Keep the parameters as it is and click Next to all windows toward end.

Forward Engineer Next

When you done with above steps, close all the open windows and come back to the starting step. Here you can see that the libraryApp will be added to the Models section. Now click on the gray section to open a local instance for MySQL.

Model Made

Below the SCHEMAS you will see the library schema. Right click on it and set it as default schema. Done!

Open Schemas

Now we have created all the tables which are empty and we need to populate them with some data. You can either do it manually or executing SQL. Here is a script that you can use to populate the tables. Open the file on MySQL workbench and execute the script.

In next tutorial I will show you how to setup the NodeJS with Express.

How to setup NodeJS and Express

In this tutorial I am going to show you how to install NodeJS and Express. I run Windows 7 on my machine, so it'll be slightly different for those on a Mac or Ubuntu, but it's principally the same thing in all cases.

Step 1. Install NodeJS

This is fairly easy. Go to Node.js website and click the green Install button. It'll detect your operating system and give you the appropriate installer. Run the installer. After installing the Node.js you can access to NPM (Node Package Manager) which lets you manage all your app's dependencies.

Step 2. Install Express

Use the application generator tool, express, to quickly create a application skeleton.Install it with the following command.

$ npm install express-generator -g
The generator should install, and since -g (global) is used the command will be available in your system path.

Display the command options with the -h option:


                        $ express -h

                        Usage: express [options] [dir]

                        Options:

                        -h, --help output usage information
                        -V, --version output the version number
                        -e, --ejs add ejs engine support (defaults to jade)
                        --hbs add handlebars engine support
                        -H, --hogan add hogan.js engine support
                        -c, --css <engine> add stylesheet <engine> support (less|stylus|compass) (defaults
                        to plain css)
                        -f, --force force on non-empty directory
Now we can use our generator to create the scaffolding for a website.
  • Open a command prompt (run cmd)
  • cd to the directory in which you wish to keep your test apps (for the purposes of this tutorial, C:\nodeApp)

The following creates an Express app named library in the C:\nodeApp working directory.

$ express library

The generated app directory structure looks like the following.

.
    ├── app.js
    ├── bin
    │   └── www
    ├── package.json
    ├── public
    │   ├── images
    │   ├── javascripts
    │   └── stylesheets
    │   └── style.css
    ├── routes
    │   ├── index.js
    │   └── users.js
    └── views
    ├── error.jade
    ├── index.jade
    └── layout.jade

    7 directories, 9 files

Note: The app structure generated by the generator is just one of the multiple ways of structuring Express apps.

Step 3: Install Dependencies

So far we have created a basic structure for our library app. in this step we need to install our dependencies. You'll note that the express-generator routine created a file called package.json in your library directory. Open this up in a text editor and it'll look like this:

{
    "name": "library",
    "version": "0.0.0",
    "private": true,
    "scripts": {
        "start": "node ./bin/www"
    },
    "dependencies": {
        "body-parser": "~1.12.4",
        "cookie-parser": "~1.3.5",
        "debug": "~2.2.0",
        "express": "~4.12.4",
        "jade": "~1.9.2",
        "morgan": "~1.5.3",
        "serve-favicon": "~2.2.1"
    }
}

This is a basic JSON file describing our app and its dependencies. We need to add a few things to it. Specifically, calls for MySQL . Let's make our dependencies object look like this:

"dependencies": {
    "body-parser": "~1.12.4",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.12.4",
    "jade": "~1.9.2",
    "morgan": "~1.5.3",
    "serve-favicon": "~2.2.1",
    "mysql":"^2.7.0"
}

Then install dependencies:

C:\nodeApp\library>npm install

Once NPM has run its course, you should have a node_modules directory which contains all of our dependencies for your app.

For running and testing our app we can use

C:\nodeApp\library>node ./bin/www
or
C:\nodeApp\library>npm start

Then load http://localhost:3000/ in your browser to access the app.

You are now running your own NodeJS webserver, with the Express engine and Jade HTML preprocessor installed.

In next tutorial I will show you how to connect to database and implement REST API.

DataBase Connection

In this tutorial I will show you how to setup the database connection and MySQL driver. I am using mysql package as node.js driver for mysql. It's time to start making changes to app.js, the heart of our application. By default Express has set it up pretty well, but we'll need to add some hooks for Monk. Here's what we start with:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
We're going to add a few things to the section at the very top, so that it looks like this:
<>var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    // Database
    var mysql = require('mysql');
    var db = mysql.createConnection({
              host : 'localhost' ,
              database : 'library',
              user : 'root',
              password : '1234'});

    db.connect();
Here we're calling the mysql module and then giving it some basic configuration parameters (including telling it where the DB lives, and which database to use – library). Now we need to make our database accessible to our various http requests. To do that add following code:
// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
    });
before this lines
app.use(logger('dev'));
app.use(bodyParser.json());
In next tutorial I will talk about front-end development of our app and routing.
Front-End development

We are going to have a single-page web app, so the we need a single page. If you open up the views folder you can see there are three files with Jade extensions in it. Jade is a templating engine and designed primarily for server side templating in node.js, however it can be used in many other environments. It is only intended to produce XML like documents (HTML, RSS etc.). If you already familiar with HTML then Jade is not hard to learn, just remember that you really have to pay attention to indentation. Most important point is to have a consistent indention when you working with Jade, otherwise Jade will throw an error. For example, in Jade, the following:

  Jade                                     HTML
body                                <body>
   h1 Title                          <h1>"Title"</h1>
   ul                               <ul>
    li Item                          <li>"Item"</li>
                                     </ul>
                                    </body>

... is very different from:
  Jade                                     HTML
body                                     <body>
   h1 Title                               <h1>"Title"
    ul                                     <ul>
     li Item                                <li>"Item"</li>
                                           </ul>
                                          </h1>
                                        </body>
 

Notice the difference in the HTML corresponding to each Jade. If you want a templating engine with true HTML syntax, you could use EJS instead.

Let's start with layout.jade. This is a template file that we're only going to make a few basic changes to. Here's how it starts:

                    doctype html
                    html
                      head
                        title= title
                        link(rel='stylesheet', href='/stylesheets/style.css')
                      body
                        block content
                    

As we need use JQuery in our app, here I will add JQuery library to this file.

                    doctype html
                    html
                      head
                        title= title
                        link(rel='stylesheet', href='/stylesheets/style.css')
                        script(src='http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')
                      body
                        block content
                    

If you recall in my first tutorial, I introduced a library database that we would like to build a library management app on top of it. My database has following tables:

  • Book,
  • Author,
  • Publisher,
  • Borrower,
  • Branch,
  • Loan, and
  • Book copy

For first step I would like to show you how to retrieve data from tables via REST API. So, I will implement GET method for Book table to retrieve list of books populated in the database.

Let's Start then!

In first step I will add a button in the index.jade which will fire an HTTP GET to retrieve all books.

                    extends layout
                    block content
                      h1= title
                      p Welcome to #{title}
                      button#getAllBooks(onClick='getAllBooks()') Get All Books

In order to perform an HTTP request, I am using a JQuery $(location) method to redirect the page to /books route.

Our index.jade should look like this,

                    extends layout
                    block content
                      h1= title
                      p Welcome to #{title}
                      button#getAllBooks(onClick='getAllBooks()') Get All Books


                      script(type='text/javascript').
                         function getAllBooks(){
                           $(location).attr('href','/books');
                         };

The purpose of this code is: if you click the Get All Books button the page will be redirected to /books. (Note: I used this method for the sake of simplicity, in next tutorials I will show how to use AJAX for this purpose).

Now we need to introduce this route in our app.js. Find the section that looks like this:

app.use('/', routes);
app.use('/users', users);

This directives are telling Express what route files to use. Now add following line after them.

app.use('/books', books);

Create a books.js file under routes folder add this code to it

                    var express = require('express');
                    var router = express.Router();

                    /* GET book page. */
                    router.get('/', function(req, res, next) {
                      var db = req.db;
                      db.query('SELECT * FROM tbl_book', function(err, results, fields){
                        if (err) {
                            res.send('error in database');
                        }else{
                            res.render('book', { title: 'List of All Books',
                                                 books:results});
                        }
                      })

                    });

                    module.exports = router;
                    

In the app.js find lines that look like this

var routes = require('./routes/index');
var users = require('./routes/users');

and add this line after them

var books = require('./routes/books');

For the final step we need to create a book.jade under views folder and add following code in it.

extends layout
block content
  h1= title
  p Here is #{title}
  ul
   each book in books
    li #{book.title}

Now open http://localhost:3000, it show look like this

getAllBooks

When you click the Get All Books button the URL will change to http://localhost:3000/books and list of book will be shown as follow

bookList

Congratulation! you have created your first REST API app with NodeJS and MySQL.

You can get the code for this tutorial from GitHub.

Using AngularJS with Material Design for NodeJS example

In previous tutorial I showed you how implement a REST API web application with NodeJS  and Express. Here I am focusing on the styling of our app and by using Google Material Design I show you how create a gorgeous app.

Material Design is a design language developed by Google. Expanding upon the "card" motifs first seen in Google Now, it is a design with increased use of grid-based layouts, responsive animations and transitions, padding, and depth effects such as lighting and shadows. For more information regarding Material Design layout guide you can visit here.

Google provides a Angular Material project with lots of demos and code samples. The Angular Material project is an implementation of Material Design in Angular.js. This project provides a set of reusable, well-tested, and accessible UI components based on the Material Design system.

Here I will show you how to add Angular Material module to your app and make a modern look and functional app.

Let's start by modifying out package.json file in order to install the Angular Material modules.

Our package.json looked like this so far

{
                      "name": "library",
                      "version": "0.0.0",
                      "private": true,
                      "scripts": {
                        "start": "node ./bin/www"
                      },
                      "dependencies": {
                        "body-parser": "~1.12.4",
                        "cookie-parser": "~1.3.5",
                        "debug": "~2.2.0",
                        "express": "~4.12.4",
                        "jade": "~1.9.2",
                        "jquery": "^2.1.4",
                        "morgan": "~1.5.3",
                        "mysql": "^2.7.0",
                        "serve-favicon": "~2.2.1"
                      }
                    }

add Angular Material Modules as follow to the dependencies object

{
                      "name": "library",
                      "version": "0.0.0",
                      "private": true,
                      "scripts": {
                        "start": "node ./bin/www"
                      },
                      "dependencies": {
                        "angular": "^1.4.1",
                        "angular-animate": "^1.4.1",
                        "angular-aria": "^1.4.1",
                        "angular-material": "^0.10.0",
                        "body-parser": "~1.12.4",
                        "cookie-parser": "~1.3.5",
                        "debug": "~2.2.0",
                        "express": "~4.12.4",
                        "jade": "~1.9.2",
                        "jquery": "^2.1.4",
                        "morgan": "~1.5.3",
                        "mysql": "^2.7.0",
                        "serve-favicon": "~2.2.1"
                      }
                    }

after updating your package.json use NPM to install them.

C:\node\library>npm install

Under the node_modules folder you will see that new Angular Material Modules will be added.

Next step is to include this modules to your app. First we need to introduce the node_modules folder to our app. Open app.js and find a line look like this

app.use(express.static(path.join(__dirname, 'public')));
and add this line after it
app.use(express.static(path.join(__dirname, 'node_modules')));

This tells express/node that the node_modules directory serves as static files for Express. Everything in it can be referenced via /, so if you also have a Angular folder in there, you might use /angular/angular.js

Now go to your layout.jade file and add following to it

link(rel='stylesheet', href='angular-material/angular-material.min.css')
                    script(src='jquery/dist/jquery.js')
                    script(src='angular/angular.min.js')
                    script(src='angular-material/angular-material.js')
                    script(src='angular-scripts/library.js')
                    script(src='angular-animate/angular-animate.min.js')
                    script(src='angular-aria/angular-aria.min.js')

So far we have installed all necessary modules and introduced them to our app. Next part I will show you how to add AngularJS to the app. (Note: I assume that your are familiar with AngularJS modules and controllers.)

AngularJS Directives

The first concept you need to know about AngularJS is what are directives.

Directives are extensions of HTML markups in form of attributes, element names, CSS class and or even HTML comments. When the AngularJS framework is loaded everything inside ng-app, it’s compiled by Angular and the directives are bound to data, events and DOM transformations.

Create an angular-scripts named folder under public folder. Make a new file named library.js under the angular-scripts folder and add this lines to it.

angular.module('library', ['ngMaterial']);

With this code we create a Angular Module named library and inject the ngMaterial into it.

After all these done, go to layout.js and find the line look like this

                        doctype html
                        html
                    
and modify it as follow
                        doctype html
                        html(ng-app = 'library')
                    
Good Job! now you have the app with Angular Material. Let's design our Get All Books button with material. Go to your index.jade file and find this line
  button#getAllBooks(onClick='getAllBooks()') Get All Books
and modify it to this
md-button#getAllBooks(class='md-raised md-primary' onClick='getAllBooks()') Get All Books

For test it open http://localhost:3000/ and it should look like this

localhost-material

It is gorgeous, isn't it! This just started, know you can benefit from all Angular power plus Material beauty and flexibility.

Using Angular Material Design for NodeJS Application

So far I have shown you how to install NodeJS, Express, MySQL and Angular Material for our simple library example. In this tutorial I will talk about AngularJS routing and services to build a CRUD (Create, Read, Update and Delete) application.

Angular Route (ngRoute)

ngRoutes module allows changing what we see in the app depending on the URL (route). It, usually, uses templates to inject the HTML into the app. $route is used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

It does not come with AngularJS core module, so we have to list it as a dependency. open package.json and add this line to the dependencies object

"angular-route": "^1.4.1"
and then run
$npm install

Now we can configure our library.js by using $routeProvider and switch between different routes. We need to inject the ngRoute dependency to our app first. Open library.js and change it as follow

angular.module('library', ['ngMaterial', 'ngRoute'])
                    .config(function($mdThemingProvider) {
                        $mdThemingProvider.theme('default')
                            .primaryPalette('blue')
                            .accentPalette('orange')
                            .warnPalette('red');
                    })
                    .config(function($routeProvider) {
                       $routeProvider.when('/books', {
                          templateUrl : 'angular-views/book.html'
                       });
                    })

In first line you can see that ngRoute is injected to our app. As you can see that I configured /books route for our application. When URL changes to localhost:3000/#/books then the templateUrl will render. Here we need to create a book.html file under public/angular-views and put our html template in it.

As I would like to show the list of our books in this template then I am using md-list for this purpose. Open book.html and put following codes to it

<div ng-controller="BookCtrl">
 <md-content>
  <md-list>
   <md-subheader class="md-no-sticky">Book List</md-subheader>
    <md-list-item class="md-3-line" ng-repeat="book in books"
                        ng-click="getBookDetails(book.bookId, $event)">
     <div class="md-list-item-text" >
      <h3>{{ book.title }}</h3>
    </div>
   </md-list-item>
  </md-list>
 </md-content>
</div>

Now that we have introduced a new route to our application then we can fetch data from our database and pass it to this view.

AngularJS Controller

AngularJS controllers are code that “controls” certain sections containing DOM elements in which they are declared. They encapsulate the behavior, callbacks and glue $scope models with views. You might have noticed in the first line of our book.html that we need a controller to control the DOMs

<div ng-controller="BookCtrl">

Under the angular-scripts folder create a folder called Book and then make a file named BookCtrl.js under it. Copy following code to BookCtrl.js then

angular.module('library').controller('BookCtrl',['$scope', function($scope){

                    }])

This controller is empty for now and does not do anything. In next part I will comeback to completer this controller.

Angular Resource (ngResource)

ngResource  is a factory which creates a resource object that lets you interact with RESTful server-side data sources.

The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.

Requires the >ngResource module to be installed.

Open your package.json and add this line to dependencies object

"angular-resource": "^1.4.1"
and do
$npm install

After you installed the ngResource module we need to inject it to our library app Open library.js and inject the ngResource as dependency to it as follow

angular.module('library', ['ngMaterial', 'ngRoute', 'ngResource'])

After these steps done you are all ready to make a REST call to our NodeJS from AngularJS.

Create a Book.js file under angular-scripts/Book folder and add following code to it

                        angular.module('library').factory('Book', ['$resource', function($resource){
                                 return $resource('/books', null, {
                                   'query': { method:'GET', isArray: true }
                                 });
                               }]);

Here, we create a service module named Book that use $resource to do the HTTP calls.

In this code return is a resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

{ 'get':    {method:'GET'},
                      'save':   {method:'POST'},
                      'query':  {method:'GET', isArray:true},
                      'remove': {method:'DELETE'},
                      'delete': {method:'DELETE'} };

For our use case, I selected the 'query' method to call a 'GET' method. This method calls /books from our NodeJS and return the array list of the books.

AngularJS Services

In our last step we need a Angular Serviceto organize and share code across our app.

Create a file named BookService.js under angular-scripts/Book folder and paste this code to it

angular.module('library').service('bookService', [ function() {

                    var isLoaded = false;
                    var map = {};

                    this.init = function(values) {
                        map = {};
                        angular.forEach(values.books, function(value){
                            map[value.bookId] = value;
                        });
                        isLoaded = true;
                    };

                    this.setValue = function(id, value) {
                        map[id] = value;
                        isLoaded = true;
                    };

                    this.deleteValue = function(id) {
                        delete map[id];
                    };

                    this.getValues = function() {
                        return map;
                    };

                    this.getValue = function(id) {
                        return map[id];
                    };

                    this.isLoaded = function(){
                        return isLoaded;
                    };

                } ]);

                

This code create a service module called booService that has a several setter/getter methods.

Now we can return to our BookCtrl.js to complete it. Open BookCtrl.js and add following code to it

angular.module('library').controller('BookCtrl',['$scope', 'Book', 'bookService',
                                     function($scope, Book, bookService) {
        Book.get(function(data){
        bookService.init(data);  // This line is optional for now
        $scope.books=data.books;
      });
}])

Notice that Book and bookService service modules has been injected to our BookCtrl. Book.get function call the query with GET method to /books and return the call back function with data. If request succeeded the callback function is called. Inside the callback function we use bookService.init method to initialize our bookService module and save the data which we can use it in future and pass it across our app (Note: This line is optional for now). Finally, we put the data on $scope.books object.This object will be part of the $scope which book.html will use it to render the book list.

Top