Sunday, January 31, 2016

NodeJS Quick Guide - Part 1

NodeJS developed by Ryan Dahl in 2009 which runs using Chrome JavaScript engine plus some libraries for asynchronous network and I/O modules.
It targets building high performance and scalable server and client applications. Node.js uses Just-in-Time compilation with the V8 JavaScript Engine.

1) Installing NodeJS
The quickest and easiest way is to install it from the web site.

Once installed from the command line you can write node or npm to ensure everything is fine.

2) NodeJS
Uses the  java script language where you can write loosely typed event based asynchronous code.
Loosely typed: means the variable types can be determined at runtime not compilation time as in Java which gives power but could lead to potential errors as you already lost the compiler error scanning.
Event-based: means you need to fire action and wait for the response/output in a function that process this output so instead of waiting the DB operation to finish fire the query and wait the response in a function, this unlike the thread based languages such as Java where you need to wait for the response , the gain is nullifying the context switching and simplify the code, which gives higher performance in throughput of the application.
So every function that requests IO has a signature like function (... parameters ..., callback) and needs to be given a callback that will be invoked when the requested operation is completed i.e. Continuation-passing style.

Note that Node is not suitable for high computation operations and it needs good design to process such operations without impacting the application.
In spite NodeJS is a single threaded, and the potential feature for fork child-processes or threads is rolled back, some modules provide a way to run some threads for high computation consuming operations one example is Threads a gogo

3) NodeJS Modules:
Node is based on modules which is similar concept to packages in Java, the modules are used by the statement:
var http = require('http');    ==> This means the http variable will be used to access the exposed functions in the http module.
The http module as an example here can expose different functions now by the following statement: exports.function_name e.g. :
exports.stop = function(){
console.log('Inside the stop function');

One of the big issues in JavaSciprt is the global variables, using the modules and exports you can control what you need to expose and any global variable is now considered local to that module and won't interfere with any similar name variable in your application.

To install modules that you need in your application, you need to use npm where you specify if you need to install the module for your application or globally for all applications by using:

npm install -g express ==> this will install express a web application framework based on the open source connect project.
if you omit -g you will install the packages locally for your application.
The modules are loaded into the node_modules folder either in your application or globally.

4) Running a hello world application
The following sample application uses the http module to start a server:
var http = require('http');
exports.start = function(){
server=http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!\n');
}).listen(8082, '');
console.log('Server is now running:');

Save it into a file name; app.js
now run node
> node
> var app=require('./app');
> app.start();

Server is now running:

Open the browser on the port 8082 using localhost:8082 you can see hello world message is printed out.
In our application we have exported start(); function() and from the node interpreter we have loaded our application module and executed this exposed start() function.
Our application uses the http module to run the http server.
You can run wrap it in another application
var app = require('./app');

Save it as app-runner.js and now run it using:
node app-runner

another way is to use the package.json file which describes your application and dependencies
create the file package.json and add the following JSON content:
{ "name": "AppRunner",
  "version": "1.0.0",
  "scripts": {
    "start": "node ./app-runner"
  "dependencies": {

NOTE: to create the file you can execute npm init to create this package.json file.
It simply shows the application name, version, start script and any dependencies should be added to that section.
Now we can run the application using the command
npm start ==> which will search for that file and run the start command.
also npm install ==> will install all the required modules in the dependencies section in the local application directory.
Finally npm list shows the installed modules for this application.

5)  Using express web application framework
Express is a Web Application Framework for node:
- Install express and express-generator
npm install express -g
npm install express-generator -g

Now use it to create a sample web application
express mytestapp   ==> This will generate the web application framework in the mytestapp folder
cd mytestapp ==> you can see the main application app.js and package.json where you need to add any future dependencies.
npm install ==> to install all required modules locally.
set DEBUG=mytestapp:* & npm start ==> in windows to start the application server
Test the application in the browser using localhost:3000

The following contains the APIs Guide for using Express:

The generated sample application contain the following main components:

1) Package.json file
In that file we can see the start script is
"scripts": {
    "start": "node ./bin/www"

If we opened this file /bin/www , we can see that it uses the app.js, do the port configurations and the initialization of http server, which means if environment variable PORT is set, use it otherwise use the port 3000.
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

We can change this port 3000 into any port e.g. 8082

2) View folder for views
We can add our views/pages here.
app.set('views', path.join(__dirname, 'views'));
The view engine to parse the views is specified as:
app.set('view engine', 'ejs');
app.set('view engine', 'jade');
You can use both options to build your view files.
Here is a quick guide for jade:
And here is a quick guide for ejs:

3) Public folder for static contents:
This folder for storing the images, stylesheets and client side java script files.

4) Router to router the requests.
var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);

one is index.js for the / path which is placed in the routes folder and another one is users.js for the path /users and is placed as well in routes folder.
You can replace content in both files to see the impact of opening both URLs and

In part II, we will continue the application exploration by adding different pages and using parameters, forms, sessions and access the database to retrieve data.

No comments:

Post a Comment