Open In App

How to build Hostel Management System using Node.js ?

Last Updated : 25 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to create a Hostel Management System. A Hostel Management System is used to manage the record of students of a college to which the college provides a hostel, where a college can view all the student data including their names, roll number, date of birth, city, phone number, father’s phone number, room number, and hostel name. College can add new students, delete the record of the existing students, and change the room number of students.

Functionalities: A college can do the following things with this Hostel Management System:

  • Display Student’s Records
  • Add New Students 
  • Delete Student’s Records
  • Get particular Student information by their Roll Number
  • Update Student’s Room Number

Approach: We are going to use Body Parser by which we can capture user input values from the form such as the student’s name, roll number, date of birth, city, phone number, father’s phone number, room number, and hostel name & store them in a collection. Then we will send the student’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 are also going to create the Delete Route for deleting records of Students, an Information Route for getting information regarding a Student by their Roll Number, and an Update Route for updating a Student’s room number.

Implementation: Below is the step-by-step implementation of the above approach.

Step 1: Project Setup

Initializes NPM: Create and Locate your project folder into the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express ejs body-parser

To install Express, EJS, and Body Parser as dependencies inside your project

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();
app.set('view engine', 'ejs');

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 %>

HTML




<!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!" })
})

Javascript




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: 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:

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

Then we can handle form data using the request object.

Step 2: Fetch Students Records: We have an array of students 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.

Javascript




const express = require('express')
const bodyParser = require('body-parser')
const students = [{
    name: "Aditya Gupta",
    rollNo: 413020,
    dataOFBirth: "29/09/2000",
    city: "Mirzapur",
    number: 6388339966,
    fatherNumber: 6388339977,
    roomNo: 23,
    hostelName: "BH-2"
}]
  
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: students
    })
})
  
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>LMS</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>
    <h1>All Books</h1>
    <table>
        <tr>
            <th>Name</th>
            <th>Roll No.</th>
            <th>Room No.</th>
            <th>Hostel Name</th>
        </tr>
        <% data.forEach(element=> { %>
            <tr>
                <td>
                    <%= element.name %>
                </td>
                <td>
                    <%= element.rollNo %>
                </td>
                <td>
                    <%= element.roomNo %>
                </td>
                <td>
                    <%= element.hostelName %>
                </td>
            </tr>
            <% }) %>
    </table>
</body>
  
</html>


Step 3: Add Students to the list: 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="Name" name="name">
    <input type="text" placeholder="Roll No." name="rollNo">
    <input type="text" placeholder="DOB" name="dateOfBirth">
    <input type="text" placeholder="City" name="city">
    <input type="text" placeholder="Number" name="number">
    <input type="text" placeholder="Father's Number" name="fatherNumber">
    <input type="text" placeholder="Room No." name="roomNo">
    <input type="text" placeholder="Hostel Name" name="hostelName">
    <button type="submit">Add</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 student’s array.

app.post("/", (req, res) => {
   const name = req.body.name
   const rollNo = req.body.rollNo
   const dateOfBirth = req.body.dateOfBirth
   const city = req.body.city
   const number = req.body.number
   const fatherNumber = req.body.fatherNumber
   const roomNo = req.body.roomNo
   const hostelName = req.body.hostelName
   
   students.push({
       name: name,
       rollNo: rollNo,
       dateOfBirth: dateOfBirth,
       city: city,
       number: number,
       fatherNumber: fatherNumber,
       roomNo: roomNo,
       hostelName: hostelName
   })
   
   res.render("home", {
       data: students
   })
})

Step 4: More Information: Updating Web Page giving a ‘more’ option: We have to create a form that sends the student roll number which data we want to fetch from the server file ‘app.js’.

<form action="/information" method="post">
    <input type="number" style="display: none;" 
        name="rollNo" value="<%= element.rollNo %>">
    <button type="submit">More Info.</button>
</form>

For getting information regarding students, we have to create an information route where we are going to fetch the requested student’s roll number and search for the element which has the same roll number, and send all data regarding that student to the web page in JSON.

app.post('/information', (req, res) => {
    var requestedRollNo = req.body.rollNo;
   
    students.forEach(student => {
        if (student.rollNo == requestedRollNo) {
            res.json(student)
        }
    })
})

Step 5: Update Room Number: Updating Web Page giving an ‘update’ option: We have to create a form that sends the student’s roll number which room number we want to update and the new room number to the server file ‘app.js’.

<form action="/update" method="post">
    <input type="number" style="display: none;" 
        name="rollNo" value="<%= element.rollNo %>">   
    <input type="number" name="newroomno">   
    <button type="submit">Update</button>
</form>  

For Updating Room Number, we have to create an updated route where we are going to fetch the student’s roll number and search for the element which has the roll number, and change the element room number property to the value get from the update form.

app.post('/update', (req, res) => {
    var requestedRollNo = req.body.rollNo;
    var newRoomNo = req.body.newroomno;
    
    students.forEach(student => {
        if (student.rollNo == requestedRollNo) {
            student.roomNo = newRoomNo;
        }
    })
    
    res.render("home", {
        data: students
    })
})

Step 6: Delete Record: Updating Web Page giving a delete option: We have to create a form that sends the student’s roll number which we want to delete to the server file ‘app.js’.

<form action="/delete" method="post">
    <input type="number" style="display: none;" 
        name="rollNo" value="<%= element.rollNo %>">
    <button type="submit">Delete</button>
</form>

For deleting a student, we have to create a delete route where we are going to fetch the requested student’s roll number and search for the element which has the same roll number, and delete the element.

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

Complete Code:

index.ejs

HTML




<!DOCTYPE html>
<html>
  
<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>
</head>
  
<body>
    <h1>All Students</h1>
  
    <table>
        <tr>
            <th>Name</th>
            <th>Roll No.</th>
            <th>Room No.</th>
            <th>Hostel Name</th>
            <th>More Info.</th>
            <th>Update Room No.</th>
            <th>Delete</th>
        </tr>
        <% data.forEach(element=> { %>
            <tr>
                <td>
                    <%= element.name %>
                </td>
                <td>
                    <%= element.rollNo %>
                </td>
                <td>
                    <%= element.roomNo %>
                </td>
                <td>
                    <%= element.hostelName %>
                </td>
                <td>
                    <form action="/information" method="post">
                        <input type="number" style="display: none;" 
                            name="rollNo" value="<%= element.rollNo %>">
                        <button type="submit">More Info.</button>
                    </form>
                </td>
                <td>
                    <form action="/update" method="post">
                        <input type="number" style="display: none;" 
                            name="rollNo" value="<%= element.rollNo %>">
                        <input type="number" name="newroomno">
                        <button type="submit">Update</button>
                    </form>
                </td>
                <td>
                    <form action="/delete" method="post">
                        <input type="number" style="display: none;" 
                            name="rollNo" value="<%= element.rollNo %>">
                        <button type="submit">Delete</button>
                    </form>
                </td>
            </tr>
        <% }) %>
    </table>
  
    <h1>Add Student</h1>
  
    <form action="/" method="post">
        <input type="text" placeholder="Name" name="name">
        <input type="number" placeholder="Roll No." name="rollNo">
        <input type="text" placeholder="DOB" name="dateOfBirth">
        <input type="text" placeholder="City" name="city">
        <input type="number" placeholder="Number" name="number">
        <input type="number" placeholder="Father's Number" 
            name="fatherNumber">
        <input type="number" placeholder="Room No." name="roomNo">
        <input type="text" placeholder="Hostel Name" name="hostelName">
        <button type="submit">Add</button>
    </form>
</body>
  
</html>


app.js

Javascript




const express = require('express')
const bodyParser = require('body-parser')
const students = [{
    name: "Aditya Gupta",
    rollNo: 413020,
    dateOfBirth: "29/09/2000",
    city: "Mirzapur",
    number: 6388339966,
    fatherNumber: 6388339977,
    roomNo: 23,
    hostelName: "BH-2"
}]
  
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: students
    })
})
  
app.post("/", (req, res) => {
    const name = req.body.name
    const rollNo = req.body.rollNo
    const dateOfBirth = req.body.dateOfBirth
    const city = req.body.city
    const number = req.body.number
    const fatherNumber = req.body.fatherNumber
    const roomNo = req.body.roomNo
    const hostelName = req.body.hostelName
  
    students.push({
        name: name,
        rollNo: rollNo,
        dateOfBirth: dateOfBirth,
        city: city,
        number: number,
        fatherNumber: fatherNumber,
        roomNo: roomNo,
        hostelName: hostelName
    })
  
    res.render("home", {
        data: students
    })
})
  
app.post('/information', (req, res) => {
    var requestedRollNo = req.body.rollNo;
    students.forEach(student => {
        if (student.rollNo == requestedRollNo) {
            res.json(student)
        }
    })
})
  
app.post('/update', (req, res) => {
    var requestedRollNo = req.body.rollNo;
    var newRoomNo = req.body.newroomno;
    students.forEach(student => {
        if (student.rollNo == requestedRollNo) {
            student.roomNo = newRoomNo;
        }
    })
    res.render("home", {
        data: students
    })
})
  
app.post('/delete', (req, res) => {
    var requestedRollNo = req.body.rollNo;
    var j = 0;
    students.forEach(student => {
        j = j + 1;
        if (student.rollNo === requestedRollNo) {
            students.splice((j - 1), 1)
        }
    })
    res.render("home", {
        data: students
    })
})
  
app.listen(3000, (req, res) => {
    console.log("App is running on port 3000")
})


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads