ACCOUNTANT
🌐 Node.js Enterprise Backend Masterclass
V8 Engine & Runtime Architecture
Node.js koi programming language ya framework nahi hai; yeh ek open-source, cross-platform JavaScript runtime environment hai jo JavaScript ko browser ke bahar OS-level privileges (file system, hardware, network sockets) ke sath run karne deta hai.
1. Under The Hood: Node.js Layer Stack
Jab aap console par node app.js execute karte hain, toh code do main core layers ke through interact karta hai:
- Google V8 Engine (C++): JavaScript syntax ko parse karta hai, abstract syntax tree (AST) banata hai aur JIT (Just-In-Time) compilation ke zariye native machine code me execute karta hai.
- libuv (C): Multi-platform C library jo asynchronous I/O operations, event loop, worker threads pool aur OS networking ko manage karti hai.
- C++ Bindings: JS API calls (jaise
fs.readFile) ko V8 ke through libuv ki native C++ system calls se bind karti hai.
libuv ke default 4-thread pool ke sahare (jise UV_THREADPOOL_SIZE se scale kiya ja sakta hai).
The Event Loop & Non-Blocking I/O Pipeline
Node.js ka high-concurrency model Event-driven, Non-blocking I/O par kaam karta hai. Synchronous execution thread ko block karti hai, jabki asynchronous calls ko Event Loop defer kar deta hai.
1. Event Loop Phases
libuv event loop har tick (iteration) me in phases se guzarta hai:
| Phase Name | Associated Callbacks / Tasks |
|---|---|
| Timers Phase | setTimeout() aur setInterval() ke scheduled callbacks execute hote hain. |
| Pending Callbacks | OS-level I/O errors (jaise TCP socket errors) handle hote hain. |
| Idle, Prepare | Internal housekeeping operations ke liye use hota hai. |
| Poll Phase | New incoming I/O events retrieve hote hain aur disk/network callbacks chalte hain. |
| Check Phase | setImmediate() ke callbacks explicitly execute hote hain. |
| Close Callbacks | Socket closures jaise socket.on('close') run hote hain. |
2. Microtasks Queue Priority (process.nextTick vs Promise)
console.log("1. Sync Start");
setTimeout(() => console.log("4. Timer Phase (setTimeout)"), 0);
setImmediate(() => console.log("5. Check Phase (setImmediate)"));
Promise.resolve().then(() => console.log("3. Microtask (Promise)"));
process.nextTick(() => console.log("2. NextTick Priority"));
console.log("6. Sync End");
// Output Sequence:
// 1. Sync Start
// 6. Sync End
// 2. NextTick Priority (Highest microtask priority)
// 3. Microtask (Promise)
// 4. Timer Phase (setTimeout)
// 5. Check Phase (setImmediate)
Module Systems: CommonJS vs ES Modules (ESM)
Modern Node.js me do standard modular patterns exist karte hain:
| Feature | CommonJS (CJS) | ECMAScript Modules (ESM) |
|---|---|---|
| Syntax | require() / module.exports |
import / export |
| Loading Model | Synchronous (Runtime parse) | Asynchronous (Pre-parse static analysis) |
| Default Status | Node.js traditional default | "type": "module" in package.json zaroori hai |
| Directory Pointers | __dirname, __filename available |
Nahi hota (Use import.meta.url) |
Enterprise ESM Export/Import Example
// mathUtils.js (ESM Module)
export const calculateTax = (amount, rate = 0.18) => amount * rate;
export default function logger(msg) {
console.log(`[LOG - ${new Date().toISOString()}]: ${msg}`);
}
// app.js
import logger, { calculateTax } from './mathUtils.js';
const tax = calculateTax(1000);
logger(`Computed GST: ${tax}`);
Low-Level Core: Buffers, Streams & File System
Badi files ko memory me ek sath load karna server ko crash kar sakta hai (Heap Out-Of-Memory). Node.js Streams chunks ke form me data stream karke low memory consumption ensure karta hai.
1. Direct Buffer Allocation
// Fixed 10-byte binary buffer allocate karna
const buf = Buffer.alloc(10);
buf.write("Node");
console.log(buf); // Raw hexadecimal representation
console.log(buf.toString('utf-8')); // "Node"
2. Memory-Safe Streaming File Pipeline
import fs from 'node:fs';
import { pipeline } from 'node:stream/promises';
import zlib from 'node:zlib';
async function compressFile(sourcePath, destPath) {
try {
await pipeline(
fs.createReadStream(sourcePath), // Source Stream
zlib.createGzip(), // Transform Stream (Compression)
fs.createWriteStream(destPath) // Destination Stream
);
console.log("File safely streamed and compressed without heap spike!");
} catch (err) {
console.error("Pipeline failure:", err);
}
}
Native HTTP Server vs Express Framework
Node.js ka native http module server primitives deta hai, jabki Express routing, body parsing aur middleware abstractions provide karta hai.
Native HTTP Implementation
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ status: 'UP', timestamp: Date.now() }));
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
});
server.listen(5000, () => console.log('Native core listening on port 5000'));
Express Middleware & Centralized Error Handling
Express application asal me middleware functions ka ek chain pattern hai. Middleware ke pass req, res, aur next ka access hota hai.
import express from 'express';
const app = express();
// Body Parser Middleware
app.use(express.json());
// Custom Logger Middleware
app.use((req, res, next) => {
console.log(`Incoming request: ${req.method} ${req.url}`);
next(); // Control passing to next middleware
});
// Route Level Logic
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }]);
});
// Centralized Error Handling Middleware (4 arguments signature)
app.use((err, req, res, next) => {
console.error(`Unhandled Error: ${err.message}`);
res.status(err.status || 500).json({
success: false,
error: err.message || 'Internal Server Error'
});
});
app.listen(3000, () => console.log('Express active on port 3000'));
REST API Design, JWT Auth & Production Capstone
Modern stateless REST API architecture me JWT (JSON Web Token) tokens ke through identity verify ki jaati hai.
Production Ready Auth Guard & API Controller
import express from 'express';
import jwt from 'jsonwebtoken';
const app = express();
app.use(express.json());
const JWT_SECRET = 'ENTERPRISE_SECRET_KEY_2026';
// 1. Auth Guard Middleware
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
if (!token) return res.status(401).json({ error: 'Access Denied: Token missing' });
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ error: 'Invalid or expired token' });
req.user = user;
next();
});
}
// 2. Authentication Route
app.post('/api/auth/login', (req, res) => {
const { username, password } = req.body;
// Hardcoded production verification logic mock
if (username === 'admin' && password === 'secret123') {
const token = jwt.sign({ username, role: 'Admin' }, JWT_SECRET, { expiresIn: '1h' });
return res.json({ success: true, token });
}
res.status(401).json({ error: 'Invalid Credentials' });
});
// 3. Protected Resource Route
app.get('/api/admin/metrics', authenticateToken, (req, res) => {
res.json({
message: `Welcome Authorized User: ${req.user.username}`,
uptime: process.uptime(),
memoryUsage: process.memoryUsage()
});
});
app.listen(8080, () => console.log('Security Gateway listening on port 8080'));
- Environment variables ke liye hamesha
dotenvya nativenode --env-file=.envuse karein. Hardcode secrets commit na karein. - Single point of failure se bachne ke liye PM2 ya Docker / Kubernetes clusters me multi-instances spawn karein.
- App crash se bachne ke liye
process.on('uncaughtException')aurprocess.on('unhandledRejection')handle karein.