CRUD with NodeJS and ExpressJS

Rajnilari2015
Posted by in Node.js category on for Beginner level | Points: 250 | Views : 1254 red flag

In this article we will learn to setup ExpressJS on top of NodeJS and perform a CRUD operation using ExpressJS.


 Download source code for CRUD with NodeJS and ExpressJS

Recommendation
Read Map and Reduce function of Javascript before this article.

Introduction

Node.js is a server side JavaScript runtime built on Chrome's V8 JavaScript engine and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. ExpressJS is a fast, unopinionated, minimalist web framework for NodeJS. In this article we will learn to setup ExpressJS on top of NodeJS and perform a CRUD operation using ExpressJS.

Environment Setup

Step 1:

Before going to perform any thing, first we need to install the NodeJS. We have installed version 4.2.2 LTS for Windows 64 machine.To check if NodeJS is properly installed or not, from the command prompt issue

 
C:\Users\niladri.biswas>node -v
v0.12.0

Step 2:

Once done, we need to create a directory say "CRUDUsingExpress".We have created that under "D:\" drive.Then issue

npm init

inside that directory.This command will create a package.json file for the application.As shown below, the moment we will issue the command it will ask for a number of things such as the name,version,description,entry point: (index.js),testcommand,git repository,keywords,author of the application,license etc.We will accept the defaults for most of the case;however for entry point: (index.js), we will specify app.js

We can figure out that "package.json" file has been created under the "D:\CRUDUsingExpress" location.Let's open the package.json file and it looks

{
  "name": "CRUDUsingExpress",
  "version": "1.0.0",
  "description": "my first experience with ExpressJS",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "RNA Team",
  "license": "ISC"
}

Step 3:

The next step is to install Express in the "D:\CRUDUsingExpress" directory and save it in the dependencies list by issuing the below command

npm install express --save

As can be figure out that, we have install the Express Modules and henceforth a new folder has been created by the name node_modules.

If we go inside that, we will find the below

Using code

1. Get record using NodeJs and ExpressJS - Get All Employee Records

In the "D:\CRUDUsingExpress" directory, create a file named app.js and add the following code to it

//add the express module
var express = require('express');

//create an instance of express module
var app = express();

//prepare the Employee data source/model
var employees =
[
   {
   "EmployeeID" :1 ,
   "EmployeeName" : "RNA Team",
   "Salary" : "200000",
   "Address" : "Bangalore"
   },
   {
   "EmployeeID" :2 ,
   "EmployeeName" : "Mahesh Samabesh",
   "Salary" : "100000",
   "Address" : "Hydrabad"
   },
   {
   "EmployeeID" :3 ,
   "EmployeeName" : "Rui Figo",
   "Salary" : "50000",
   "Address" : "Dallas"
   },
   {
   "EmployeeID" :4 ,
   "EmployeeName" : "Indradev Jana",
   "Salary" : "456789",
   "Address" : "Los Angles"
   },
   {
   "EmployeeID" :5 ,
   "EmployeeName" : "Suresh Shailesh",
   "Salary" : "1234567",
   "Address" : "Patna"
   }
 ];

//Get the Employee records
app.get('/', function (req, res) {
  res.send(employees);
});

  //run the server
  var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Server started and is listening at :> http://%s:%s', host, port);
});

Code Explanation

In the beginning, we have imported the needed modules and prepared the model data.Since express routes are based on HTTP verbs, so the app.get() method fetches the records from the URI specified.And finally the app starts a server and listens on port 3000 for connection. It will respond with the Employee Records for requests to the root URL (/) or route.

Now let us run the app with the below command

node app.js

Let us open a browser and type in the URL http://localhost:3000/ and the output will be

2. Get single record using NodeJS and ExpressJS - Get Employee Records whose EmployeeId

Assume we want to pass the EmployeeId as parameter while doing HTTP GET operation.In that case the Employee records will be filtered based on the EmployeeId passed at runtime. Henceforth, we need to have a new route. The code will be as shown below.

app.get('/:EmployeeID', function (req, res) {
  
  var employeeID = req.params.EmployeeID;

   //Get Employee Records whose EmployeeID = get the EmployeeID at runtime
    var filteredEmployee = [];

    for(var i= 0; i< employees.length; i++){

      if(employees[i].EmployeeID == employeeID){
        filteredEmployee.push(employees[i]);        
      }
    } //end Loop
    employees = filteredEmployee;  
    res.send(employees);
});

The result

We have passed the EmployeeID at runtime and filter the records.Internally, Express converts a route to regular expression.

We can also pass multiple parameters as shown under

    app.get('/:Param1/:Param2?', function (req, res) {
    // code
  }
3. Insert record using NodeJS and ExpressJS - Add a new Employee

Now we will insert a new employee to the record.The only code segment that needs to be added is shown below

//insert a employee record

 //create a new employee record
 var newEmployee = [
   {
   "EmployeeID" :6 ,
   "EmployeeName" : "Arina Biswas",
   "Salary" : "555555",
   "Address" : "Kolkata"
   }
];

// add the new record to the existing collection
employees.push(newEmployee);

The output will be

4. Update record using NodeJS and ExpressJS - Update an existing Employee

Suppose we want to update the Salary and Address field of an Employee based on the EmployeeID provided at runtime.We can use the below code

//update Employee Record
app.get('/:EmployeeID/:Salary/:Address', function (req, res) {
  
  var employeeID = req.params.EmployeeID; 
  var employeeSalary =  req.params.Salary; 
  var employeeAddress = req.params.Address;
  console.log(employeeID + "-------" + employeeSalary +"--------" + employeeAddress);

  //Get Employee Records whose EmployeeID = get the EmployeeID at runtime 

    for(var i= 0; i< employees.length; i++){

      if(employees[i].EmployeeID == employeeID){

        employees[i].Salary = employeeSalary;
        employees[i].Address = employeeAddress;                
      }
    } //end Loop    
    res.send(employees);
});

Interesting thing to note is that how we are passing multiple parameters

'/:EmployeeID/:Salary/:Address'

Once we get the records, we are updating those.Below is the result from browser

5. Delete record using NodeJs and ExpressJS - Delete an existing Employee

Suppose we want to delete the second and third record.The below code segment will help to do so

//delete a record
var employeeDeleted = employees.splice(1, 2);
console.log(employeeDeleted);

In the console itself we can figure out that the second record is not in the list

The output in browser

Reference

1) ExpressJS

2) NodeJS

Conclusion

In this article, we have look into as how we can setup NodeJS & ExpressJS and perform a CRUD operation. Hope this article will be helpful. Thanks for reading.  The source code in the zipped file attached, feel free to download and use it.

Recommendation
Read Masking in JQuery after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Raja on: 12/5/2015 | Points: 25
Which version of NodeJs you are using Rajnilari, looks like Janso has tried and his example is not working. See the facebook comment below.

Thanks
Posted by: Rajnilari2015 on: 12/5/2015 | Points: 25
It is a working example and the node version is v0.12.0 (:

Login to post response

Comment using Facebook(Author doesn't get notification)