Sunday, 29 June 2014

Building a web app with node js




NodeJS is an event driven javaScript framework that makes writing asynchronous code a piece of cake! For small apps and a limited user base, this is almost magical – the code can be churned out fast, it is clean and it is perfectly unit testable. The purpose of this blog is not to sell node js though, we’ll instead look at how an application could be built easily.
The applications I work on are primarily client-server, like web apps, or mobile apps with a backend. So here’s what my toolkit with node js looks like


  • Express JS: Sinatra like web framework that gives basic structure to the web app
  • Sequelize JS: ORM framework
  • Require JS: for modularization
  • Node DB Migrate module: just like rails db migrations
  • Mocha JS: For unit tests
  • Chai JS: For test assertions
  • Crypto: For encryptions
  • Angular JS: For the front end
  • MySQL: database
Lets keep the front end out of scope for this article and only focus on getting an app that can serve JSON over REST.

Setting up the environment

  1. Install nodejs
  2. Next, we need expressjs
  3. Run the following
    1
    2
    3
    4
    5
    npm install -g express
    # create the app now. we'll call it 'myapp'
    express myapp
    cd myapp
    node app.js
  4. You should now see something like this “Express server listening on port 3000″
  5. Yay! You now have a basic Express JS app running!

Configuring the app

  1. The ExpressJS guide is a pretty good resource for getting started, so I would recommend that you read through it.
  2. Next, add the following in package.json under dependencies:
    1
    2
    3
    4
    5
    6
    7
    8
    "mysql": "*",
    "supervisor": "*",
    "db-migrate": "*",
    "sequelize": "*",
    "requireindex": "*",
    "mocha": "*",
    "crypto": "*",
    "chai": "*"
  3. Save package.json and run “npm install”
  4. Supervisor module is a great module for development environments and it auto reloads the app on change, so you dont have to restart your node server every time. To run the app using supervisor, just use “supervisor app.js”
  5. Requireindex is a nice module that helps get all objects from  a directory into a single object, without adding a “require” for each file
  6. Add the error handler in app.js (as described in expressjs guide)
    1
    2
    3
    4
    app.use(function(err, req, res, next){
      console.error(err.stack);
      res.send(500, 'Something broke!');
    });
  7. Run the app again and access using http://localhost:3000.

Adding database support

  1. Install mysql
  2. We already have the node module included in package.json (mysql), so the app is now ready to start talking to the database
  3. We’ll use node db migrate module to set up the database.
  4. Create a file database.json under myapp. The contents should look as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    {
      "dev": {
        "driver": "mysql",
        "user": "root",
        "database": "myapp"
      },
      "test": {
        "driver": "mysql",
        "user": "root",
        "database": "myapp_test"
      },
      "production": {
        "driver": "mysql",
        "user": "root",
        "database": "myapp"
      }
    }
  5. Create a db.js in the myapp directory with the following contents:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    var express = require('express'),
        Sequelize = require("sequelize");
    var app = express();
    var env = app.get('env') == 'development' ? 'dev' : app.get('env');
    // db config
    var fs = require('fs');
    var dbConfigFile = __dirname + '/database.json';
    var data = fs.readFileSync(dbConfigFile, 'utf8');
    var dbConfig = JSON.parse(data)[env];
    var password = dbConfig.password ? dbConfig.password : null;
    var sequelize = new Sequelize(dbConfig.database, dbConfig.user, password, { logging: true });
    exports.sequelize = sequelize