Mini Project based on Node js & Express — student-manager-ui
What it does (in browser): show students list, add student, edit student, delete student, filter by city.
Backend: Express + file storage (students.json) using fs/promises.
Frontend: HTML/CSS/JS served from Express (so students open http://localhost:5000 and see UI).
1. Project files & structure
student-manager-ui/
├── index.js // Express server (routes, middleware)
├── data.js // Custom module: read/write students.json
├── events.js // EventEmitter: logs when a student is added
├── students.json // data store (auto-created if missing)
├── event-log.txt // event log (created at runtime)
├── package.json
└── public/
├── index.html
├── styles.css
└── script.js
2. How to create & run (quick steps)
Create folder and move into it:
mkdir student-manager-ui cd student-manager-uiInitialize npm and install express:
npm init -y npm install expressCreate the files below (copy each code block into the named file).
Start the server:
node index.js(Or add
"start": "node index.js"topackage.jsonscripts and runnpm start.)Open browser:
http://localhost:5000
3. Backend code (files)
index.js — main Express server
// index.js
const express = require('express');
const path = require('path');
const os = require('os');
const { getAllStudents, getStudentById, addStudent, updateStudent, deleteStudent } = require('./data');
const events = require('./events'); // EventEmitter instance (listener logs to file)
const app = express();
const PORT = process.env.PORT || 5000;
// --- Simple logger middleware (demonstrates middleware)
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
next();
});
// parse JSON bodies (express.json is modern and current)
app.use(express.json());
// Serve static frontend files from /public
app.use(express.static(path.join(__dirname, 'public')));
// --- Routes (all under /api)
app.get('/api/students', async (req, res) => {
try {
const city = req.query.city; // query param demonstration
let students = await getAllStudents();
if (city) {
students = students.filter(s => s.city && s.city.toLowerCase() === city.toLowerCase());
}
res.json(students);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Server error reading students' });
}
});
app.get('/api/students/:id', async (req, res) => {
try {
const id = Number(req.params.id); // route param demonstration
const student = await getStudentById(id);
if (!student) return res.status(404).json({ error: 'Student not found' });
res.json(student);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/students', async (req, res) => {
try {
const { name, city } = req.body;
if (!name || !name.trim()) return res.status(400).json({ error: 'Name is required' });
const newStudent = await addStudent({ name: name.trim(), city: city ? city.trim() : '' });
// Emit event (events.js listens and writes to event-log.txt)
events.emit('studentAdded', newStudent);
res.status(201).json(newStudent);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Could not add student' });
}
});
app.put('/api/students/:id', async (req, res) => {
try {
const id = Number(req.params.id);
const { name, city } = req.body;
if (!name || !name.trim()) return res.status(400).json({ error: 'Name is required' });
const updated = await updateStudent(id, { name: name.trim(), city: city ? city.trim() : '' });
if (!updated) return res.status(404).json({ error: 'Student not found' });
res.json(updated);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Could not update student' });
}
});
app.delete('/api/students/:id', async (req, res) => {
try {
const id = Number(req.params.id);
const removed = await deleteStudent(id);
if (!removed) return res.status(404).json({ error: 'Student not found' });
res.json({ message: 'Student deleted' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Could not delete student' });
}
});
// Optional: show some server info using os module
app.get('/info', (req, res) => {
res.json({
platform: os.platform(),
arch: os.arch(),
uptime_seconds: os.uptime()
});
});
// fallback 404 for unknown API paths
app.use('/api', (req, res) => {
res.status(404).json({ error: 'API route not found' });
});
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
console.log(`Open http://localhost:${PORT} in the browser to use the UI`);
});
What index.js demonstrates
express.json()middleware (parsing JSON body)custom logging middleware
route params
:id(req.params)query params (
req.query.city)async/await in route handlers with
try/catcherror handlingserving static frontend with
express.staticosmodule for server info
data.js — data access module (custom module using fs/promises + path)
// data.js
const fs = require('fs').promises;
const path = require('path');
const filePath = path.join(__dirname, 'students.json');
// Ensure file exists and return parsed data
async function readDataFile() {
try {
const raw = await fs.readFile(filePath, 'utf-8');
return JSON.parse(raw);
} catch (err) {
if (err.code === 'ENOENT') {
// File doesn't exist — create with empty array and return []
await fs.writeFile(filePath, '[]', 'utf-8');
return [];
}
// JSON parse error or other error: propagate
throw err;
}
}
async function writeDataFile(data) {
await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf-8');
}
async function getAllStudents() {
return await readDataFile();
}
async function getStudentById(id) {
const students = await readDataFile();
return students.find(s => s.id === id) || null;
}
async function addStudent({ name, city }) {
const students = await readDataFile();
const id = students.length ? students[students.length - 1].id + 1 : 1;
const newStudent = { id, name, city };
students.push(newStudent);
await writeDataFile(students);
return newStudent;
}
async function updateStudent(id, { name, city }) {
const students = await readDataFile();
const idx = students.findIndex(s => s.id === id);
if (idx === -1) return null;
students[idx].name = name;
students[idx].city = city;
await writeDataFile(students);
return students[idx];
}
async function deleteStudent(id) {
const students = await readDataFile();
const idx = students.findIndex(s => s.id === id);
if (idx === -1) return false;
students.splice(idx, 1);
await writeDataFile(students);
return true;
}
module.exports = { getAllStudents, getStudentById, addStudent, updateStudent, deleteStudent };
What data.js demonstrates
Custom module using
module.exports/require(modularity)fs/promises+path.join(safe cross-platform file paths)async/await and robust file read/write with ENOENT handling
JSON data store (simple file-based DB for teaching)
events.js — EventEmitter that logs when a student is added
// events.js
const EventEmitter = require('events');
const fs = require('fs').promises;
const path = require('path');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
const logPath = path.join(__dirname, 'event-log.txt');
emitter.on('studentAdded', async (student) => {
const line = `${new Date().toISOString()} | Added: id=${student.id}, name=${student.name}, city=${student.city || ''}\n`;
try {
await fs.appendFile(logPath, line, 'utf-8');
} catch (err) {
console.error('Failed to write event log:', err);
}
});
module.exports = emitter;
What events.js demonstrates
Node
eventsmodule andEventEmitterlistening for custom events (
studentAdded) and doing side effects (append toevent-log.txt)using
fs.promises.appendFileand handling write errors
4. Frontend files (served from /public)
Create folder public/ and add the three files below.
public/index.html
<!-- public/index.html -->
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Student Manager</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="container">
<h1>Student Manager</h1>
<form id="addForm">
<input id="nameInput" placeholder="Name" required />
<input id="cityInput" placeholder="City" />
<button type="submit">Add Student</button>
</form>
<div class="controls">
<input id="filterCity" placeholder="Filter by city (press Enter)" />
<button id="refreshBtn">Refresh</button>
</div>
<ul id="studentsList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
public/styles.css
/* public/styles.css */
body { font-family: Arial, sans-serif; background:#f7f7f7; margin:0; padding:20px;}
.container { max-width:700px; margin:0 auto; background:white; padding:20px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,.08);}
h1 { margin-top:0; }
form { display:flex; gap:8px; margin-bottom:12px; }
form input { flex:1; padding:8px; }
form button { padding:8px 12px; }
.controls { display:flex; gap:8px; margin-bottom:12px; }
#studentsList { list-style:none; padding:0; }
.student { display:flex; justify-content:space-between; padding:8px; border-bottom:1px solid #eee; }
.student .left { display:flex; gap:8px; align-items:center; }
.student button { margin-left:8px; }
public/script.js
// public/script.js
const apiBase = '/api/students';
const listEl = document.getElementById('studentsList');
const addForm = document.getElementById('addForm');
const nameInput = document.getElementById('nameInput');
const cityInput = document.getElementById('cityInput');
const filterCity = document.getElementById('filterCity');
const refreshBtn = document.getElementById('refreshBtn');
async function fetchJSON(url, options) {
const res = await fetch(url, options);
if (!res.ok) {
// try to read JSON error body, else use status text
const errBody = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(errBody.error || errBody.message || res.statusText);
}
return res.json().catch(() => null);
}
async function loadStudents() {
const city = filterCity.value.trim();
const url = city ? `${apiBase}?city=${encodeURIComponent(city)}` : apiBase;
try {
const students = await fetchJSON(url);
renderList(students);
} catch (err) {
alert('Error fetching students: ' + err.message);
}
}
function renderList(students) {
listEl.innerHTML = '';
if (!students || students.length === 0) {
listEl.innerHTML = '<li>No students found</li>';
return;
}
students.forEach(s => {
const li = document.createElement('li');
li.className = 'student';
li.innerHTML = `
<div class="left">
<strong>${s.name}</strong>
<span>(${s.city || '—'})</span>
</div>
<div class="right">
<button data-id="${s.id}" class="edit">Edit</button>
<button data-id="${s.id}" class="delete">Delete</button>
</div>
`;
listEl.appendChild(li);
});
// attach handlers
document.querySelectorAll('.delete').forEach(btn => {
btn.onclick = async (e) => {
const id = e.target.dataset.id;
if (!confirm('Delete this student?')) return;
try {
await fetchJSON(`${apiBase}/${id}`, { method: 'DELETE' });
await loadStudents();
} catch (err) {
alert('Delete failed: ' + err.message);
}
};
});
document.querySelectorAll('.edit').forEach(btn => {
btn.onclick = async (e) => {
const id = e.target.dataset.id;
const newName = prompt('New name:');
if (!newName) return;
const newCity = prompt('New city (optional):');
try {
await fetchJSON(`${apiBase}/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName, city: newCity })
});
await loadStudents();
} catch (err) {
alert('Update failed: ' + err.message);
}
};
});
}
addForm.onsubmit = async (e) => {
e.preventDefault();
const name = nameInput.value.trim();
const city = cityInput.value.trim();
if (!name) return alert('Name is required');
try {
await fetchJSON(apiBase, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, city })
});
nameInput.value = '';
cityInput.value = '';
await loadStudents();
} catch (err) {
alert('Add failed: ' + err.message);
}
};
filterCity.onkeydown = (e) => {
if (e.key === 'Enter') loadStudents();
};
refreshBtn.onclick = loadStudents;
// initial load
loadStudents();
What the frontend demonstrates
A simple UI to interact with the REST API
fetch()usage with async/awaitHandling HTTP errors and showing messages
Using query param to filter by city
CRUD UI (Create, Read, Update, Delete) calling server endpoints
5. students.json
You can create it yourself with:
[]
If you don't create it, data.js will create it automatically the first time the server runs.
6. Step-by-step explanation (project flow)
Startup & project flow
- Student opens
http://localhost:5000→ Express servespublic/index.html(express.static).
[ It means serving static files and frontend-backend together. ]
Adding a student
Frontend
script.jssendsPOST /api/studentswith{ name, city }.index.jsroute handles the request, validates name, callsaddStudent(indata.js).data.jsreadsstudents.json(usingfs/promises), appends new student with an incrementalidand writes back.index.jsemitsstudentAddedevent;events.jslistens and appends a line toevent-log.txt.
Teaches: POST route, request body parsing, file read/write, custom modules, events.
Listing / filtering
Frontend does
GET /api/studentsorGET /api/students?city=Delhi.index.jsreadsreq.query.cityand filters results on server.
Teaches: query params and server-side filtering.
Single student & editing
GET /api/students/:idshows route param usage;PUT /api/students/:idupdates.
Teaches: route params and update flow.
Delete
DELETE /api/students/:idremoves student from JSON.
Teaches: RESTful DELETE and response codes.
Middleware / logging
- The logger middleware logs every incoming request (
console.log).
Teaches: middleware usage and request lifecycle.
Error handling
All route handlers use
try/catchand return appropriate HTTP status codes:400for bad input (missingname)404when student not found500for unexpected server errors
data.jshandlesENOENTwhen file missing and creates file automatically.
Teaches: robust error handling in sync/async code and clear API error messages.
Events
- When a student is added,
events.emit('studentAdded', newStudent)triggers a listener which appends toevent-log.txt.
Teacheseventsmodule and side-effect logging.
Modules & code structure
index.js(server),data.js(data access),events.js(EventEmitter) — each a separate module for clarity.
Teaches: modular code,module.exportsandrequire.
7. How error handling is done (explicit)
Validation errors: checked immediately (e.g., missing
name) → respond400with a readable message.Not found: read operations that return
nulllead to404.I/O errors: wrapped in
try/catch→500returned so clients know it’s a server problem.File missing (ENOENT):
data.jshandles it and initializesstudents.jsonto[]to avoid crashes.Event logging errors:
events.jsappendFileis inside try/catch and prints to console if logging fails — this prevents the whole API from failing because the log write failed.
Teacher note: explain why returning clear status codes matters (200/201/400/404/500) and how the frontend uses them to show messages.
8. Things to ask students to try (class activities)
Add students, see
students.jsonandevent-log.txtupdated.Try POST with empty
name→ get400response and alert.Use filter box (city) and press Enter to filter results (tests query params).
Edit a student (Edit button) and verify JSON changed.
Delete a student.
Manually break
students.json(write invalid JSON) and try to load — discuss what error happens and how to fix (teach JSON parse errors).Replace file storage with MongoDB later (explain why we would need DB for production due to concurrency and scaling).
9. Notes for working professionals (best practices)
This project uses file-based storage for teaching. In production use a proper DB (MongoDB) for concurrency, indexing, and scaling.
If high concurrency is expected, add file-locking or move to DB — plain read/modify/write sequence has race conditions.
Add centralized error middleware to format errors consistently.
Add input sanitization and stricter validation in real apps.
Use logging libraries (winston/pino) for structured logs in production (not
console.log).
10. Troubleshooting & tips
If
students.jsonmissing,data.jswill create it. If you intentionally corrupt it,JSON.parsefails — show students how to open file and fix.If port 5000 already used, either stop other app or change
PORTenv variable.If static files not loading, check
public/folder path andexpress.static(path.join(__dirname, 'public')).
🔔 Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas — 📩 Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, 🎥 Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. 🚀
About the author
- Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟
Comments
Join the discussionNo comments yet. Be the first to comment.
Node.js Mastery: From Basics to Real-world Projects
Learn Node.js from basics to advanced with Express, REST APIs, MongoDB, and real projects. Perfect for beginners, frontend devs, and backend aspirants—simple language, real-world examples.

