Dec 4, 2015

NodeJS quick guide for beginner

NodeJS is a platform which encourages good software practices out of the box like async and IOC. NodeJS is async by nature. This can be achieved in Asp.Net MVC but that's not default behavior. NodeJS (and express) support middleware similar to pipeline/filters in asp. For someone coming from .Net background here is a quick way to correlate node with .Net.

IIS - Node.exe
C# - JavaScript
ASP.NET MVC Razor-Express Vash
ASP.NET Web API - Express
SignalR - WebSockets

There are number of IDE available for node development, one of which is open source plugin for visual studio. This may be more comfortable for someone coming from .Net background. Refer following for more details on this
       https://github.com/Microsoft/nodejstools

NodeJS is executed under google v8 engine. V8 compiles JavaScript source code directly into machine code when it is first executed.

Module
A module encapsulates related code into a single unit of code. In Node.js, files and modules are in one-to-one correspondence. As an example, following code loads the module controller.js
 
 var controller = require("./controller");

In the above code require("./controller") returns an object which represent (modular) code encapsulated in controller.js (or controller\index.js). Each file (module) has access to module.exports object. You can assign properties to this object which require will return. So the content of controller.js could be
 
 module.exports.myFirstName = "rahul";
 module.exports.myLastName = "raj";
 module.exports.myName = {lastName : "rahul"}

You can access this like.
 
 var controller = require("./controller");
 console.log(controller.myFirstName);

In this case code in controller.js is executed only once when you do require("./controller.js"). The other way is to assign export object as a function
 
 module.exports = function () {
  return "my first name is rahul";
 };

This can be referenced and executed as following. In this example every time you execute controller(), that function will be called.
 
 var controller = require("./controller");
 console.log(controller());

You can also assign constructor method to the export object
 
 module.exports = function () {
  this.myFirstName = "rahul";
  this.myLastName = "raj";
 };

In this case you can use it like this in app.js
 
 var controller = require("./controller");
 var control = new controller();
 console.log(control.myFirstName);

One of my favourite way is to use self executing anonymous function
 
 (function (controller){
  controller.init = function () {
   return "my first name is rahul";
  };
 })(module.exports);

This way we are passing in module.exports as controller. So now inside the anonymous function you can use controller to add any property bag. You may also want to have index.js in every folder and have all your module referenced in index.js, so anyone outside that folder (set of module) just reference index.js.

Express
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
 
 var express = require("express");
 var app = express();

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
 
 app.get("/create", function (req, res, next)

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)): For static file to be accessible from browser you need to set static resource folder. This is build-in middleware
 
 app.use(express.static(__dirname + "/public"));  //__dirname is the rooth directory name of the application

The other common middlewares are following. These are third-party middleware
 
 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(bodyParser.json()); // parse application/json
 app.use(expressValidator());
 app.use(session({...}));
 app.use(flash());

Refer following for more details on using express middleware
http://expressjs.com/en/guide/using-middleware.html

For using template engines with Express you need to set following
 
 app.set("view engine", "vash");

Grunt
Its a javascript task runner. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting, etc, the easier your job becomes.

npm install grunt-cli -g

It looks for gruntfile.js file in the root folder where nodejs is running. this will not be used during run time, its purely development asset. Few of the grunt plugin which i recently used are
grunt-nodemon
grunt-mocha-test
grunt-contrib-watch
grunt-jsbeautifier

Bower 
Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.

Npm
It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.

Mocha, Chai, Sinon
Mocha sets up and describes test suites and Chai provides convenient helpers to perform all kinds of assertions against your JavaScript code. Sinon is a great JavaScript library for stubbing and mocking such external dependencies and to keep control on side effects against them. run test in all the files which are in test folder by adding chai.should(), all javascript object get property should

No comments:

Post a Comment