Skip to main content

Mini Project based on Node js & Express — student-manager-ui

Updated 11 min readMarkdown
Part of seriesNode.js Mastery: From Basics to Real-world Projects

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)

  1. Create folder and move into it:

     mkdir student-manager-ui
     cd student-manager-ui
    
  2. Initialize npm and install express:

     npm init -y
     npm install express
    
  3. Create the files below (copy each code block into the named file).

  4. Start the server:

     node index.js
    

    (Or add "start": "node index.js" to package.json scripts and run npm start.)

  5. 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/catch error handling

  • serving static frontend with express.static

  • os module 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 events module and EventEmitter

  • listening for custom events (studentAdded) and doing side effects (append to event-log.txt)

  • using fs.promises.appendFile and 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/await

  • Handling 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 serves public/index.html (express.static).
    [ It means serving static files and frontend-backend together. ]

Adding a student

  • Frontend script.js sends POST /api/students with { name, city }.

  • index.js route handles the request, validates name, calls addStudent (in data.js).

  • data.js reads students.json (using fs/promises), appends new student with an incremental id and writes back.

  • index.js emits studentAdded event; events.js listens and appends a line to event-log.txt.
    Teaches: POST route, request body parsing, file read/write, custom modules, events.

Listing / filtering

  • Frontend does GET /api/students or GET /api/students?city=Delhi.

  • index.js reads req.query.city and filters results on server.
    Teaches: query params and server-side filtering.

Single student & editing

  • GET /api/students/:id shows route param usage; PUT /api/students/:id updates.
    Teaches: route params and update flow.

Delete

  • DELETE /api/students/:id removes 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/catch and return appropriate HTTP status codes:

    • 400 for bad input (missing name)

    • 404 when student not found

    • 500 for unexpected server errors

  • data.js handles ENOENT when 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 to event-log.txt.
    Teaches events module 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.exports and require.

7. How error handling is done (explicit)

  • Validation errors: checked immediately (e.g., missing name) → respond 400 with a readable message.

  • Not found: read operations that return null lead to 404.

  • I/O errors: wrapped in try/catch → 500 returned so clients know it’s a server problem.

  • File missing (ENOENT): data.js handles it and initializes students.json to [] to avoid crashes.

  • Event logging errors: events.js appendFile is 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)

  1. Add students, see students.json and event-log.txt updated.

  2. Try POST with empty name → get 400 response and alert.

  3. Use filter box (city) and press Enter to filter results (tests query params).

  4. Edit a student (Edit button) and verify JSON changed.

  5. Delete a student.

  6. Manually break students.json (write invalid JSON) and try to load — discuss what error happens and how to fix (teach JSON parse errors).

  7. 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.json missing, data.js will create it. If you intentionally corrupt it, JSON.parse fails — show students how to open file and fix.

  • If port 5000 already used, either stop other app or change PORT env variable.

  • If static files not loading, check public/ folder path and express.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! 🌟

No comments yet. Be the first to comment.

More from this blog