-
Event Loop Architecture
- Single-threaded, non-blocking I/O
- LibUV, Event Queue, Call Stack
- Microtasks vs Macrotasks
// Understand this execution order console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4'); // Output: 1, 4, 3, 2
-
Modules System
- CommonJS vs ES Modules
- Module caching, circular dependencies
- Built-in modules (fs, path, http, etc.)
-
Node.js Internals
- V8 JavaScript Engine
- Buffer and Streams
- Child Processes & Worker Threads
// Master these core modules:
const fs = require('fs/promises'); // File System
const path = require('path'); // Path handling
const crypto = require('crypto'); // Cryptography
const stream = require('stream'); // Streams API
const child_process = require('child_process'); // Child processes- Singleton Pattern (for database connections)
- Factory Pattern (object creation)
- Observer Pattern (EventEmitter)
- Middleware Pattern (Express/Connect)
- Repository Pattern (data access)
// 1. Callbacks (avoid callback hell)
function asyncOperation(callback) {
process.nextTick(callback);
}
// 2. Promises
const promiseExample = () => new Promise((resolve, reject) => {
// Async operation
});
// 3. Async/Await
async function fetchData() {
try {
const data = await promiseExample();
return data;
} catch (error) {
// Error handling
}
}
// 4. Event Emitters
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
emitter.on('event', () => {});const http = require('http');
const https = require('https');
// Raw HTTP server
const server = http.createServer(async (req, res) => {
// Handle routing, middleware, parsing
});
// Advanced patterns:
// - REST API design
// - WebSocket servers (ws, socket.io)
// - GraphQL servers (Apollo, express-graphql)
// - gRPC servers- SQL (PostgreSQL with pg/Sequelize/Knex)
- NoSQL (MongoDB with Mongoose)
- Redis for caching/sessions
- Elasticsearch for search
// Example: Advanced MongoDB with Mongoose
const mongoose = require('mongoose');
// Schema design, indexes, transactions
const userSchema = new mongoose.Schema({
email: { type: String, unique: true, index: true },
data: mongoose.Schema.Types.Mixed
}, {
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true }
});
// Transactions
const session = await mongoose.startSession();
session.startTransaction();
try {
await User.create([{ name: 'John' }], { session });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
}// Cluster mode
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
const cpus = os.cpus().length;
for (let i = 0; i < cpus; i++) {
cluster.fork();
}
} else {
require('./server.js');
}
// Worker Threads for CPU-intensive tasks
const { Worker, isMainThread } = require('worker_threads');- Helmet.js for headers
- Rate limiting
- Input validation/sanitization
- JWT authentication best practices
- SQL injection prevention
// Test pyramid: Unit → Integration → E2E
const { describe, it, before, after } = require('mocha');
const { expect } = require('chai');
const sinon = require('sinon');
// Mocking, stubs, spies
const sandbox = sinon.createSandbox();
const stub = sandbox.stub(api, 'call');- Docker containers for Node.js
- PM2 for process management
- Nginx reverse proxy
- Load balancing strategies
- Health checks, graceful shutdown
-
Microservices Architecture
- Service discovery
- Message queues (RabbitMQ, Kafka)
- API gateways
-
Clean Architecture/DDD
- Separation of concerns
- Dependency injection
- Repository pattern
-
Event-Driven Architecture
- Event sourcing
- CQRS pattern
- Event bus implementation
- Real-time Chat App (Socket.io, Redis)
- E-commerce API (Microservices, Payment integration)
- Streaming Service (Video/audio streaming with buffers)
- Web Scraper (Puppeteer, Cheerio, rate limiting)
- CLI Tool (Commander.js, Inquirer.js, chalk)
- Debugging: Node Inspector, ndb
- Profiling: clinic.js, 0x
- Logging: Winston, Pino with structured logging
- Validation: Joi, class-validator
- API Documentation: Swagger/OpenAPI
- Monitoring: Prometheus, Grafana
- Tracing: Jaeger, OpenTelemetry
- APM: New Relic, Datadog
- LeetCode (Node.js problems)
- Advent of Code (Algorithmic challenges)
- Open Source Contributions (Express, Koa, etc.)
- Understand Event Loop phases
- Can debug memory leaks
- Implement custom streams
- Build a CLI tool with native modules
- Create a C++ addon
- Setup Docker multi-stage builds
- Implement circuit breaker pattern
- Write performance tests
- Configure CI/CD for Node.js
- Deploy to Kubernetes
- Morning: Read Node.js source code (GitHub)
- Afternoon: Build a micro-package/library
- Evening: Solve 1 algorithmic problem with Node.js
- Weekly: Contribute to open source Node.js project
- Blocking the Event Loop (synchronous ops in async context)
- Memory Leaks (global variables, closures)
- Promise Anti-patterns (nested .then, ignoring errors)
- Improper Error Handling (uncaught exceptions)
- Security Misconfigurations
- Event Loop and libuv
- Streams and Buffers
- Cluster vs Worker Threads
- Middleware implementation
- Database optimization
- Authentication strategies
- Caching techniques