MCA
NODE.JS ECOSYSTEM // ASYNCHRONOUS // EVENT-DRIVEN // SERVER-SIDE JAVASCRIPT // NODE.JS ECOSYSTEM // ASYNCHRONOUS // EVENT-DRIVEN // SERVER-SIDE JAVASCRIPT //
BACK TO HOME
v20+

NODE.JS
CORE_

SERVER-SIDE V8 RUNTIME

CONCEPTS

Core Architecture

⚙️
  • V8 Engine
  • Event Loop
  • Single-Threaded
  • Non-Blocking I/O

Async Programming

  • Callbacks
  • Promises
  • Async/Await
  • Event Emitters

Web Frameworks

🌐
  • Express.js
  • Fastify
  • NestJS
  • Koa

Data Handling

💾
  • Streams
  • Buffers
  • File System (fs)
  • MongoDB / Mongoose
  • PostgreSQL / Prisma

CORE_MODULES

01

fs

File system interaction

fs.readFile('data.txt', cb)
02

http

Create web servers

http.createServer(req, res)
03

path

Work with file paths

path.join(__dirname, 'public')
04

events

Custom event handling

const emitter = new EventEmitter()
05

crypto

Hashing & cryptography

crypto.createHash('sha256')
06

os

Operating system utility

os.cpus().length

PATTERNS

Middleware Pattern

Functions that have access to request and response objects

MVC Architecture

Separate logic into Models, Views, and Controllers

Dependency Injection

Pass dependencies to modules rather than hardcoding

Event-Driven

Components communicate via an event bus

Service Layer

Abstract business logic away from controllers

EXERCISES

Build an Express REST APIeasy
Create a CLI Tool using Commandermedium
Implement JWT Authenticationmedium
Real-time Chat with Socket.iohard
Write a Web Scraper Scripthard

SYNTAX_DEMO

server.js
// ============================================
// NODE.JS CORE & BUILT-IN MODULES
// ============================================

const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

// 1. Basic HTTP Server (No Framework)
const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'Online', service: 'Node API' }));
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});
// server.listen(3000, () => console.log('Server running on port 3000'));

// 2. File System (Async/Await)
const { readFile, writeFile } = require('fs/promises');

async function manageFiles() {
  try {
    const data = await readFile(path.join(__dirname, 'data.txt'), 'utf8');
    const hash = crypto.createHash('sha256').update(data).digest('hex');
    await writeFile(path.join(__dirname, 'hash.txt'), hash);
    console.log('File encrypted and written successfully.');
  } catch (err) {
    console.error('File operation failed:', err);
  }
}

// 3. Event Emitters
const EventEmitter = require('events');
class PaymentService extends EventEmitter {}
const payment = new PaymentService();

payment.on('purchase', (amount) => {
  console.log(`Sending receipt for purchase of $${amount}`);
});

payment.emit('purchase', 19.99);

// ============================================
// EXPRESS.JS FRAMEWORK 
// ============================================

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

// Middleware
app.use(express.json()); // Body parser

// Custom Application-Level Middleware
const requestLogger = (req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
};
app.use(requestLogger);

// Routing & Controllers
const users = [];

app.get('/api/users', (req, res) => {
  res.status(200).json({ success: true, count: users.length, data: users });
});

app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  
  if (!name || !email) {
    return res.status(400).json({ success: false, error: 'Please provide name and email' });
  }
  
  const newUser = { id: Date.now(), name, email };
  users.push(newUser);
  
  res.status(201).json({ success: true, data: newUser });
});

// Parameterized Route
app.get('/api/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  
  if (!user) {
    return res.status(404).json({ success: false, error: 'User not found' });
  }
  
  res.status(200).json({ success: true, data: user });
});

// Global Error Handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ success: false, error: 'Something broke internally!' });
});

// app.listen(5000, () => console.log('Express app running properly'));

DIRECTORY