Understanding routing of expressJS in Node.JS

For further advanced reading you may want to prefer REST API using express .

I have started learning Node.JS and for web apps most popular ExpressJS framework. Well few call it big library as well. As learner does not matter whether big library or framework, let’s start exploring.

While exploring express realised that one of the most vital concept of express is Routing. In this post I will try to share my learning on express Routing with you. If you are starting with Express feel free to have a look on Setup Express and run first application in Node.js .

Let us assume that you have created first site using express. In root folder you will find App.js file. Go ahead and open App.js. In top you will find two modules express and http are imported along with other modules.

clip_image001

 

Express uses HTTP verbs to perform routings hence HTTP module is imported and of course to work with express framework express module is imported. Since express routes are based on HTTP verbs so method names are also matched. Refer following table for same.

clip_image003

You can create a route as below,

 

clip_image004

 

Above route will be accessed using HTTP GET on application being accessed on base address. As shown below you can see that plain text is sent in response object from express application.

clip_image005

In Express if you have two route paths with same address rather throwing error it will pick route path defined first in App.js

Assume you want to pass parameter while doing HTTP GET operation in above route then you have two choices. Either create two routes as shown below.

clip_image007

Second route will be accessed when a parameter will be passed while performing HTTP GET. So if you access application as below you will get served from second route path.

clip_image008

You may want to create only one route path making id as optional. Id can be make optional by putting it inside : id? This can be done as below,

clip_image010

Route path created above can handle both types of request either with parameter or without parameter. We are checking for the parameter and on basis of that different response being delivered. So bottom line is combination of 😕 makes parameter optional.

Express converts a route to regular expression internally. Input parameter can be parsed using req.params.id where is name of the parameter.

You can pass more than one parameters as shown below. We are making op as optional by placing it inside : ?

clip_image012

With second optional parameter application can be fetched as below. As you see we are passing id and op both while doing HTTP GET.

clip_image013

Express allow you to created REST based route path using *. So if I want to pass any number of parameters doing HTTP GET that can be done appending *

clip_image014

You can pass any number of parameters to access above created route path now.

clip_image015

If you try to access route which is not created then you will get error message as below. loo route is not there in rout paths so express is throwing error as below,

clip_image016

You can create routes with other HTTP VERBS . Method names are matched with HTTP verbs as discussed in beginning of this post.

clip_image017

You can test other operations like PUT , DELETE , POST in fiddler. This is how you can work with routing in express. For further advanced reading you may want to prefer REST API using express . Do not get overwhelmed with Visual Studio there in this post and follow the post to create REST API in any of your favourite code editor. I hope this post is useful to you.

If you want to create routes using crossroads then this post may help you

Create a Router in Node.js using crossroads

Setup Express and run first application in Node.js

In this post we will take a step by step look in setting up Express and creating first application. I assume that you have already installed Node. If not then go ahead and install from here

Once node.js is successfully installed, you can install Express framework by running npm install express on command prompt.

clip_image001

After installing express, I will recommend to create a new folder and change directory to newly created folder. I have created a folder expressjs and going to create a site named mysite using express framework. To create site run command express mysite . mysite is name of the site.

image

On successful execution of above command you will get suggestion as below that several files has been created.

clip_image003

Next to install dependency. To install that navigate to site directory. You can navigate to site directory using cd mysite. In mysite directory

clip_image004

It will install all dependency in mysite directory.

clip_image005

After successful installation of dependency you should get npm info ok message as shown in above figure. Now you can run created website by express using node.

clip_image006

In browser navigate to server on port 3000 and you will get basic site created using express up and running.

clip_image007

This is how you can set up express to create sites running on node.js. In further posts we will look into routing, app.js, routing path, http verbs. I hope you like this post. Thanks for reading.

Create REST API on Node.js using Visual Studio

Find Source Code on Github

In this post I am not going to explain, what is REST? I assume you are already aware of REST concepts hence on this post to create REST API on Node.js which will perform CRUD operations. I am going to use Visual Studio to create Node Application and before you move ahead in this post, recommend you to read

Getting started with Node.js development in Visual Studio

After reading above article when you are done with setting up Visual Studio for Node.js go ahead and create a Node Application by selecting Blank Express Application template from JavaScript language section

image

Once project is created right click on the public\javascripts folder and add a new JavaScript file. You are free to give any file name, I am giving data.js .

Before you work with data.js I recommend you to read below post

Working with modules

First we are going to create data and CRUD operation on that. Keep in mind that we are going to expose CRUD operation as REST API on a JavaScript Array. In real projects you may want to perform these operations on database.

To start with I have created an array as below,


var product =
[
 {
 "id" :1 ,
 "productName" : "Pen",
 "productPrice" : "200",
 'productStock' : "false"
 },
 {
 "id" :2 ,
 "productName" : "Pencil",
 "productPrice" : "200",
 "productStock" : "false"
 },
 ];

Fetch Records

Let us start with writing function to return products. If you notice function is taking two parameters req and res. We send data in HTTP response with res.send . In this case we are sending JSON object product as HTTP response.


exports.getProducts = function(req,res){

 res.send(product);
 };

Add Record

To add record we need to read data coming in HTTP request. We can read that using req.body. Client will append JSON data to get added in product array in request body. After reading request body we are just pushing data in array using push method.

 


exports.addProduct = function(req,res)
{
 var data = req.body;
 product.push(data);
 res.send(product);
}

Delete Record

To delete record we need to read query parameter coming in URL as HTTP request. We can read that using req.params. Once we have id to delete a product, I am just putting some logic to delete it from products array. Keep in mind that in real project and API this logic should be better. Once product is deleted successfully we are sending updated product JSON object in HTTP response.


exports.deleteProduct = function(req,res)
{

 var id = parseInt(req.params.id)-1;
 var itemdeleted = product.splice(id,1)
 if(itemdeleted===undefined)
 {
 res.send("Not Deleted");
 }
 else
 {
 ;
 res.send(product);
 }
}

Update Record

To update record we need to read query parameter coming in URL as HTTP request. We can read that using req.params. Once we have id to update a product, we will read data to be updated in req.body. After that I am just putting some logic to update item in products array. Keep in mind that in real project and API this logic should be better. Once product is updated successfully we are sending updated product JSON object in HTTP response.


exports.updateProduct = function(req,res)
{
 var id = parseInt(req.params.id)-1;
 var productToUpdate = product[id];
 var data = req.body;

 if(productToUpdate===undefined)
 {

res.send("Not Updated");
 }
 else
 {
 productToUpdate.productName = data.productName;
 productToUpdate.productPrice = data.productPrice;
 productToUpdate.productStock = data.productStock;

res.send(product);
 }

}

 

Just we created CRUD operation which we will expose as REST API. Putting all together data.js which contains logic for CRUD would be as below,

data.js

var product =
[
 {
 "id" :1 ,
 "productName" : "Pen",
 "productPrice" : "200",
 'productStock' : "false"
 },
 {
 "id" :2 ,
 "productName" : "Pencil",
 "productPrice" : "200",
 "productStock" : "false"
 },
 ];
exports.getProducts = function(req,res){

 res.send(product);
 };

exports.addProduct = function(req,res)
{
 var data = req.body;
 product.push(data);
 res.send(product);
}

exports.deleteProduct = function(req,res)
{

 var id = parseInt(req.params.id)-1;
 var itemdeleted = product.splice(id,1)
 if(itemdeleted===undefined)
 {
 res.send("Not Deleted");
 }
 else
 {
 ;
 res.send(product);
 }
}

exports.updateProduct = function(req,res)
{
 var id = parseInt(req.params.id)-1;
 var productToUpdate = product[id];
 var data = req.body;

 if(productToUpdate===undefined)
 {

res.send("Not Updated");
 }
 else
 {
 productToUpdate.productName = data.productName;
 productToUpdate.productPrice = data.productPrice;
 productToUpdate.productStock = data.productStock;

res.send(product);
 }

}

 

So far we have created business logic to be exposed as REST API. Now we need to add various routes in app.js. These routes will call functions from data.js module. We are going to map ROUTES to business logic as below,

image

Open app.js and add this code to load data.js module. [write all below code in app.js]


var data = require('./public/javascripts/data.js');

Once module is loaded use bodyParse to parse request body.


app.use(express.bodyParser());

If you notice we created project using Express Template. So here Node.js Express Framework router is being used. In last step to create REST API we need to add routes to application.


app.get('/products',data.getProducts);
app.post('/products',data.addProduct);
app.delete('/products/:id',data.deleteProduct);
app.put('/products/:id',data.updateProduct);

Each route is calling a function in data module. If you notice when we added a route for HTTP POST operation which is calling addProducts function. In this function we are creating a product.

Yes it is done. You have created REST API on Node.JS using Visual Studio. To test it you have various options. You can either use

  • CURL
  • Fiddler
  • Create a client to work with service (in next post we will do this)

So let us test created REST API in Fiddler and browsers. We can test HTTP GET in browser by pressing F5 and navigate to baseURL/products

image

Next let us use fiddler to perform POST, PUT and DELETE. To perform POST or create a product select Composer, from drop down select POST operation. Set URL, set Content-Type and in Request-Body construct a JSON to add as product.

image

When you perform this operation as a response you will get updated products as response. You can verify this in browser as well.

image

As you performed POST in the same way in fiddler you can perform DELETE and PUT. So I hope you must have realised by now that creating REST API on Node.js using Visual Studio is very simple. In next post we will consume this created REST service in different kind of clients. I hope you find this post useful. Thanks for reading.

Find Source Code on Github

Create a Router in Node.js using crossroads

Routers are very important in any web server. Primary function of a Router is to accept request and on basis of requested URL trigger desired process.

Consider a rough example in that client is requesting

http://abc.com/users/myprofile and there request may serve from URL http://abc.com/node/2 assuming user is stored in node with id 2.

image

In Node.js you can create router using many publicly available modules. Some of them are as follows,

  • Express
  • Director
  • Bouncy
  • Backbone
  • Crossroads

In this post let us create a router using Crossroads. To start with install crossroads module in application using npm crossroads or you may want to use mange modules in Visual Studio as well.

Once crossroads module is installed you need to load crossroads module in application.

image

You can add route in application using addRoute function. I have added route which takes two parameters.


crossroads.addRoute('/{type}/:id:',function(type,id){

 if(!id)
 {
 result = "Acess informtion about all " + type;
 return;
 }
 else
 {
 result = "Acess informtion about "+ type + "with id" +id ;
 return;
 }

 });

In above route

  • Type is parameter need to be passed to request server
  • Id is optional parameter to be passes to request server. Optional parameters should be enclosed with ::

Second parameter of addRoute is a callback function. In this callback you need to write logic to work with different requests with different parameters in request. As you see in above example we are constructing string on basis of requested URL.

If you write result in response then you will get output as below,

image

image

In first request we are passing only type (student) whereas in second request we are passing both type and optional id.

So when adding route you can have parameters in request as

image

If you want to add a route with REST segment then you can do that as follows,

clip_image002

Now on requesting server you will get id passed as optional REST segment.

image

Putting all together you can create a Router in Node.js application using crossroad as below,


var http = require('http');
var crossroads = require('crossroads');
var result ;
crossroads.addRoute('/{type}/:id*:',function(type,id){

 if(!id)
 {
 result = "Acess informtion about all " + type;
 return;
 }
 else
 {
 result = "Acess informtion about "+ type + "with id" +id ;
 return;
 }

 });

http.createServer(function(request,response){
 crossroads.parse(request.url) ;
 response.writeHead(200);
 response.write(result);
 request.on('end',function(){
 response.end("Req End");
 });

}).listen(8080,function(){

 console.log("server started");

 });

In above code apart from creating server we are parsing request URL as well using parse function

clip_image001

In this you can create a router. Off course you can use other modules to create router as well. When working with web applications router of express framework is very powerful. I hope you find this post useful. Thanks for reading.

Error: `doctype 5` is deprecated, you must now use `doctype html`: Node.js Express App bug solved

I am using Visual Studio to create Node.js application. I created a Node project by selecting Blank Express Application project template from JavaScript project type.

clip_image002

After creating project I pressed F5 to run application. On running application I got following error

clip_image003

Solving this error is very easy. From views folder in project open layout.jade. You will find below code

clip_image005

First line of code contains doctype 5. You need to replace it with doctype html

clip_image007

Now go ahead and press F5 to run application. You should not get above exception and in browser expected output you will get as below,

clip_image008

I hope you find this post useful. Thanks for reading.

How to upload file in Node.js

In this post we will take a look on uploading a file on a web server created using Node.js. stream in Node.js makes this task super easy to upload files or for that matter working with any data transfer in between server and client.

To upload file we will work with two modules http and fs. So let us start with loading these two modules in application,


var http = require('http');
var fs = require('fs');

Once modules are loaded go ahead and create web server


http.createServer(function(request,response){

 }).listen(8080);

So far we are good and now we wish to perform following steps,

  1. Create a destination write stream. In this stream content of uploaded file will be written.
  2. We want to write back to client percentage of data being uploaded

First requirement can be done using pipe. pipe is event of stream in Node.js. And request is a readable stream. So we will use pipe event to write request to readable stream.


var destinationFile = fs.createWriteStream("destination.md");
 request.pipe(destinationFile);

Second requirement is to write back in response percentage of data uploaded. To do that first read total size if the file getting uploaded. That can be done by reading content-length (line no 1 in below code snippet). After that in data event of request we will update uploadedBytes which is in the beginning zero (line no 2). In data event of request we are calculating percentage and writing it back in the response.


var fileSize = request.headers['content-length'];
 var uploadedBytes = 0 ;

request.on('data',function(d){

 uploadedBytes += d.length;
 var p = (uploadedBytes/fileSize) * 100;
 response.write("Uploading " + parseInt(p)+ " %\n");

});

Putting all together your app should contain below code to upload a file and response back percentage uploaded.


var http = require('http');
var fs = require('fs');
 http.createServer(function(request,response){
 response.writeHead(200);
 var destinationFile = fs.createWriteStream("destination.md");
 request.pipe(destinationFile);

var fileSize = request.headers['content-length'];
 var uploadedBytes = 0 ;

request.on('data',function(d){

 uploadedBytes += d.length;
 var p = (uploadedBytes/fileSize) * 100;
 response.write("Uploading " + parseInt(p)+ " %\n");

});

request.on('end',function(){
 response.end("File Upload Complete");
 });

}).listen(8080,function(){

 console.log("server started");

 });

On command prompt start server as below,

clip_image002

Now let us use curl –upload-file to upload a file on server.

clip_image004

As you see that while file is being uploaded percentage of data uploaded is returned back to client. So in this way you can upload a file to server created using Node.js. I hope you find this post useful. Thanks for reading.

Create Echo Server in Node.js

Creating HTTP server in Node.js is very simple. In this post we will learn to create an echo server using Node.js.

Before we move ahead, let us understand what an echo server is. In echo server, client sends data to server and server returns back same data to server.

image

To create echo server, let us first create HTTP server. We need to export http module and then using createServer function HTTP server can be created.


var http = require('http');

http.createServer(function(request,response){

}).listen(8080);

To create echo server we will work with streams. In Node.js request and response are readable and writeable stream respectively.

image

Request readable stream got two events data and end. These events will be used to read data coming from client. These events can be attached to request stream as below,


request.on('data',function(message){

 });

 request.on('end',function(){

 response.end();
 });

Once we have created server and attached events to request, then we can write data from client back to client by writing to response as below,


request.on('data',function(message){

 response.write(message);

 });

Putting above discussion together full source code to create echo server is as follows,


var http = require('http');

http.createServer(function(request,response){

 response.writeHead(200);

request.on('data',function(message){

 response.write(message);

 });

 request.on('end',function(){

 response.end();
 });
 }).listen(8080);

So you can run application on command prompt using node

clip_image001

When web server is running then using curl post data to server as below. You will get response back as below,

clip_image002

In above approach we used data and end event to echo data back to client. Node.js provides another way to write back requested data to response using pipe. You can create echo server using pipe as below,


var http = require('http');

http.createServer(function(request,response){

 response.writeHead(200);
 request.pipe(response);

}).listen(8080);


Above application will send data back to client. In these two ways you can create echo server in Node.js. I hope you find this post useful. Thanks for reading.

Inheritance in Node.js

Read other posts on Node.js here

In this post we will take a look on inheritance of objects in Node.js. We will learn to use utility module to achieve inheritance in Node.js. However keep in mind that you can write plain JavaScript to achieve inheritance in Node as well. You can use Object.create() to inherit one object to another in Node.js also.

In this post we will learn to use util module to achieve inheritance in Node.js. Very first you need to import util module in your application

image

After importing util module, let us say you have an object as below,


function Student()
{

 this.name = "G Block";
 this.age = 40;
};

Just for demonstration let us add function in object using prototype,


Student.prototype.Display= function(){
 console.log(this.name + " is " + this.age + " years old");
 };

Next we are going to create ArtsStudent object which will inherit Student object.


function ArtsStudent()
{
 ArtsStudent.super_.call(this);
 this.subject = "music";
 };

util.inherits(ArtsStudent,Student);

Second line of code in ArtsStudent object is very important,

image

If you don’t call constructor of parent object as shown in above code snippet then on trying to access properties of parent object will return undefined.

In last line ArtStudent inherits Student using util.inherits() function ,

image

Next you can create instance of ArtsStudent and call function of parent object as below,


var a = new ArtsStudent();
a.Display();

Inheritance can be chained to any order. If you want you can inherit object from ArtsStudent as well. Inherited object will contain properties from both ArtsStudent and Student objects. So let us consider one more example,


function ScienceStudent()
{
 ScienceStudent.super_.call(this);
 this.lab = "Physics";
}

util.inherits(ScienceStudent,ArtsStudent);
var b = new ScienceStudent();
b.Display();

In above example ScienceStudent object inherits both Student and ArtsStudent objects. In this way you can work with inheritance in Node.js using util module. I hope you find this post useful. Thanks for reading.

Getting started with Node.js development in Visual Studio

Setup Environment on Windows machine for Node.js Development [Set up Sublime Text]

Yes you love node.js. You love event driven development and yes multi thread is old fashioned now. Your new found love is ASYNCHRONOUS. Asynchronous everything, even reading file system. As all we know Microsoft loves Developers. So in Build they decided to give node.js development support in Visual Studio 2012 and Visual Studio 2013.

In this post we will take step by step look on setting up Visual Studio for node.js development. You need to follow below steps,

Step 1

Download in install Node.js from http://nodejs.org/

Step 2

Next download and install Node.js for Visual Studio from here,

https://nodejstools.codeplex.com/releases/view/114437

You need to make sure that you select correct option to download. I am going to install Node on Visual Studio 2012.

image

After successful installation you will get below confirmation message of successful installation.

clip_image001[6]

 

After installation above said pieces you are good to go and start developing Node.js in Visual Studio. On launching Visual Studio in JavaScript language category, you will get various project templates related to Node.js

image

There are five different project templates available.

image

You can create Node.js application web based by selecting, Blank Node.js Web Application project template.

clip_image002

On successful creation of project you will get following files in project. Solution explorer will look like below,

clip_image003

server.js will contain code and entry point of application. By default server.js contains following code

clip_image002[6]

You just need to press F5 to run with debug or Ctrl+F5 to run without debugging. This default code will give you following output in browser

clip_image003[7]

And whereas debugger is listening on port 5858.

image

So we experienced that working with Node.js in Visual Studio is very smooth. You just need to press F5 to run application and can put a breakpoint and debug the code. As you see in below image that breakpoint is being hit.

image

You can find that intellisense will work as expected. This completely support intellisense for Node.js

image

Other thing you will notice that Node.js debugger support complete stack trace.

 

clip_image002[8]

 

Exporting existing Node.js project

You can create existing Node.js project from existing Node.js project by creating a project choosing template From Existing Node.js code

clip_image002[10]

On next screen you need to browse to existing project folder. You can also select files types to be included. After providing these two input click on Finish.

image

You will find existing project has been exported to new project.

In this way you can set up Visual Studio 2012 to work with Node.js development. I hope you find this post useful. Thanks for reading.