Open In App

How to Build Employee Management System using Node.js ?

Last Updated : 18 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An Employee Management System (EMS) is a crucial tool for businesses to efficiently manage their workforce. It allows companies to handle tasks like displaying employee details, adding new employees, removing existing ones, promoting employees, and updating salaries. In this article, we’ll walk through the process of building a basic EMS using Node.js, Express, and EJS for rendering views.

Prerequisites:

Functionality of EMS

  • Display Employee: Show the list of all employees along with their details.
  • Add Employee: Add new employees with their name, post, and salary.
  • Remove Employee: Delete an employee from the system.
  • Promote Employee: Update an employee’s post or designation.
  • Update Salary: Modify an employee’s salary.

Approach

We are going to use Body Parser by which we can capture user input values from the form such as the employee’s name, post, and salary &  store them in a collection. Then we will send the employee’s data to the web page using EJS. EJS is a middleware that makes it easy to send data from your server file (app.js or server.js) to a web page. We will also create the Discharge Route for discharging the patients.

We will utilize the following technologies and libraries:

  • Node.js: For the server-side logic.
  • Express: A web framework for building the API and handling requests.
  • EJS: A template engine for rendering views with dynamic data.
  • Body Parser: Middleware to parse incoming request bodies

Steps to Setup the Project

Step 1: Initialize the NodeJS application using the following command

npm init

Step 2: Install the necessary packages/libraries in your project using the following commands.

npm install express ejs body-parser

Project Structure:

Screenshot-2024-06-17-151955


The updated dependencies in package.json file will look like:

"dependencies": {
"body-parser": "^1.20.2",
"ejs": "^3.1.10",
"express": "^4.19.2",
}

Create Server File

Create an ‘app.js’ file, inside this file require the Express Module, and create a constant ‘app’ for creating an instance of the express module, then set the EJS as the default view engine.

const express = require('express');
const app = express();

Rearrange Your Directories

It is required to use ‘.ejs’ as an extension for the HTML file instead of ‘.html’ for using EJS inside it. Then you have to move every ‘.ejs’ file in the views directory inside your root directory. EJS is by default looking for ‘.ejs’ files inside the views folder.

Use EJS variable: Inside your updated .ejs file, you have to use EJS Variables to receive values from your server file. You can declare variables in EJS like

<%= variableName %>
<!DOCTYPE html>
<html>

<head>
<title>Page Title</title>
</head>

<body>
<%= variableName %>
</body>

</html>

Send data to a variable

Inside your server file ( app.js or index.js ), you can send an EJS file along with some data by using the render method.

app.get("/", (req, res) => {
res.render("home", { variableName: "Hello Geeks!" })
})
Node
const express = require("express");
const app = express();
app.set("view engine", "ejs");

app.get("/", (req, res) => {
  res.render("home", { variableName: "Hello Geeks!" });
});

app.listen(3000, (req, res) => {
  console.log("App is running on port 3000");
});

Fetching data from form to app.js

Step 1: To receive input values of a form, we have to use a node package named body-parser.

Install body-parser:

npm install body-parser

Require body-parser module:

const bodyParser = require('body-parser')

And then using the above installed packages:

app.use( bodyParser.json() );      
app.use(bodyParser.urlencoded({
extended: true
}));

Then we can handle form data using the request object.

Step 2: Fetch Employee Records:

We have an array of employees with different properties. Let’s send the array to our web page. In the previous step, we just sent a value to the variable, now we are sending the complete array.

Node
// app.js

const express = require("express");
const bodyParser = require("body-parser");
const employees = [
  {
    employeeId: "1",
    employeeName: "Aditya Gupta",
    employeePost: "Manager",
    userSalary: "43000",
  },
  {
    employeeId: "2",
    employeeName: "Vanshita Jaiswal",
    employeePost: "Assistant Manager",
    userSalary: "21000",
  },
];

const app = express();

app.set("view engine", "ejs");

app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

app.get("/", function (req, res) {
  res.render("home", {
    data: employees,
  });
});

app.listen(3000, (req, res) => {
  console.log("App is running on port 3000");
});

Since we have so many elements inside our array and we have to print each of them so we have to use For Each Loop to loop through every single element inside our collection and display the details.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Employee Management System</title>

    <style>
        table {
            font-family: arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }
        td,
        th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }

        tr:nth-child(even) {
            background-color: #dddddd;
        }
    </style>
</head>

<body>
    <h2>Employee Management System</h2>
    <table>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Post</th>
            <th>Salary</th>
        </tr>
        <% data.forEach(element=> { %>
            <tr>
                <td>
                    <%= element.employeeId %>
                </td>
                <td>
                    <%= element.employeeName %>
                </td>
                <td>
                    <%= element.employeePost %>
                </td>
                <td>
                    <%= element.employeeSalary %>
                </td>
            </tr>
            <% }) %>
    </table>

</body>

</html>

Step 3: Add Employee:

For this, we have to create a form and handle the form data inside our ‘app.js’ file using Body Parser.

<form action="/" method="post">
<input type="text" placeholder="Employee Name"
name="employeeName">
<input type="text" placeholder="Employee Post"
name="employeePost">
<input type="text" placeholder="Employee Salary"
name="employeeSalary">
<button type="submit">Submit</button>
</form>

Handle form data inside ‘app.js’: We have to fetch values from a form using req.body.valueName, and then arrange it like an object and push it inside our employee’s array.

app.post("/", (req, res) => {
const inputEmployeeId = employees.length + 1;
const inputEmployeeName = req.body.employeeName
const inputEmployeePost = req.body.employeePost
const inputEmployeeSalary = req.body.employeeSalary
employees.push({
employeeId: inputEmployeeId,
employeeName: inputEmployeeName,
employeePost: inputEmployeePost,
employeeSalary: inputEmployeeSalary
})
res.render("home", {
data: employees
})
})

Step 4: Remove Employee

Updating Web Page giving a Remove option: We have to create a form that sends the employee’s name which we want to Remove to the server file ‘app.js’.

<form action="/https/www.geeksforgeeks.org/delete" method="post">
<input type="text"
style="display: none;"
name="employeeId"
value="<%= element.employeeId %>">
<button type="submit">Delete</button>
</form>

For Removing an employee, we have to create a Remove route where we are going to fetch the requested employee’s name and search for the employee who has the same name, and delete the element.

app.post('/delete', (req, res) => {
var requestedEmployeeId = req.body.employeeId;
var j = 0;
employees.forEach(employee => {
j = j + 1;
if (employee.employeeId === requestedEmployeeId) {
employees.splice((j - 1), 1)
}
})
res.render("home", {
data: employees
})
})

Step 5: Update Post and Salary

Updating Web Page giving an Update option: We have to create a form that sends the employee’s name which we want to Update.

<form action="update" method="post">
<input type="text" placeholder="Employee Id"
name="employeeId">
<input type="text" placeholder="Employee Name"
name="employeeName">
<input type="text" placeholder="Employee Post"
name="employeePost">
<input type="text" placeholder="Employee Salary"
name="employeeSalary">
<button type="submit">Update</button>
</form>

For Updating an employee, we have to create an Update route where we are going to fetch the requested employee’s name and search for the employee who has the same name, and Update the element with new data such as salary or post.

app.post('/update', (req, res) => {
const requestedEmployeeId = req.body.employeeId;
const inputEmployeeName = req.body.employeeName
const inputEmployeePost = req.body.employeePost
const inputEmployeeSalary = req.body.employeeSalary

var j = 0;
employees.forEach(employee => {
j = j + 1;
if (employee.employeeId === requestedEmployeeId) {
employee.employeeName = inputEmployeeName,
employee.employeePost = inputEmployeePost,
employee.employeeSalary = inputEmployeeSalary
}
})
res.render("home", {
data: employees
})
})

Example: Below is the complete code to build Library Management System using Node.js:

HTML
// home.ejs

<!DOCTYPE html>
<html>

<head>
  <title>
    	Employee Management System
  </title>
</head>
<style>
  table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
  }

  td,
  th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
  }

  tr:nth-child(even) {
    background-color: #dddddd;
  }
</style>

<body>
  <h2>Employee Management System</h2>
  <table>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Post</th>
      <th>Salary</th>
      <th>Delete</th>
    </tr>
    <% data.forEach(element=> { %>
      <tr>
        <td>
          <%= element.employeeId %>
        </td>
        <td>
          <%= element.employeeName %>
        </td>
        <td>
          <%= element.employeePost %>
        </td>
        <td>
          <%= element.employeeSalary %>
        </td>
        <td>
          <form action="/delete" method="post">
            <input type="text" style="display: none;" 
                   name="employeeId" 
                   value="<%= element.employeeId %>">
            <button type="submit">Delete</button>
          </form>
        </td>
      </tr>
      <% }) %>
  </table>

  <h2>Add Employee</h2>

  <form action="/" method="post">
    <input type="text" placeholder="Employee Name" 
           name="employeeName">
    <input type="text" placeholder="Employee Post" 
           name="employeePost">
    <input type="text" placeholder="Employee Salary" 
           name="employeeSalary">
    <button type="submit">Submit</button>
  </form>

  <h2>Update Employee</h2>

  <form action="/update" method="post">
    <input type="text" placeholder="Employee Id" 
           name="employeeId">
    <input type="text" placeholder="Employee Name" 
           name="employeeName">
    <input type="text" placeholder="Employee Post" 
           name="employeePost">
    <input type="text" placeholder="Employee Salary" 
           name="employeeSalary">
    <button type="submit">Update</button>
  </form>
</body>

</html>
Node
// app.js

const express = require("express");
const bodyParser = require("body-parser");
const employees = [
  {
    employeeId: "1",
    employeeName: "Aditya Gupta",
    employeePost: "Manager",
    employeeSalary: "43000",
  },
  {
    employeeId: "2",
    employeeName: "Vanshita Jaiswal",
    employeePost: "Assistant Manager",
    employeeSalary: "21000",
  },
];

const app = express();

app.set("view engine", "ejs");

app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

app.get("/", function (req, res) {
  res.render("home", {
    data: employees,
  });
});

app.post("/", (req, res) => {
  const inputEmployeeId = employees.length + 1;
  const inputEmployeeName = req.body.employeeName;
  const inputEmployeePost = req.body.employeePost;
  const inputEmployeeSalary = req.body.employeeSalary;

  employees.push({
    employeeId: inputEmployeeId,
    employeeName: inputEmployeeName,
    employeePost: inputEmployeePost,
    employeeSalary: inputEmployeeSalary,
  });

  res.render("home", {
    data: employees,
  });
});

app.post("/delete", (req, res) => {
  var requestedEmployeeId = req.body.employeeId;
  var j = 0;
  employees.forEach((employee) => {
    j = j + 1;
    if (employee.employeeId === requestedEmployeeId) {
      employees.splice(j - 1, 1);
    }
  });
  res.render("home", {
    data: employees,
  });
});

app.post("/update", (req, res) => {
  const requestedEmployeeId = req.body.employeeId;
  const inputEmployeeName = req.body.employeeName;
  const inputEmployeePost = req.body.employeePost;
  const inputEmployeeSalary = req.body.employeeSalary;

  var j = 0;
  employees.forEach((employee) => {
    j = j + 1;
    if (employee.employeeId == requestedEmployeeId) {
      (employee.employeeName = inputEmployeeName),
        (employee.employeePost = inputEmployeePost),
        (employee.employeeSalary = inputEmployeeSalary);
    }
  });
  res.render("home", {
    data: employees,
  });
});

app.listen(3000, (req, res) => {
  console.log("App is running on port 3000");
});

Step to run the application: Inside the terminal type the  following command

node app.js

Output:



Next Article

Similar Reads