- 🏭 Cluster Module
- 🧵 Worker Threads
- 🔁 Streams
⚠️ Error Handling- 🔐 Security Best Practices
- 🧒 Child Processes
- ⚡ Optimizing Node.js Performance
Node.js runs on a single-threaded event loop, but with the cluster module, we can create multiple worker processes that share the same server port, utilizing multi-core CPUs efficiently.
- 🖥️ High CPU-bound applications
- ⏳ Applications that require parallel request processing
const cluster = require('cluster');
const http = require('http');
const os = require('os');
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end("Hello from Worker " + process.pid);
}).listen(3000);
}- ❓ How does the
clustermodule work in Node.js? - ❓ What is the difference between
clusterandworker_threads? - ❓ Can a clustered process share memory?
Unlike the cluster module, worker_threads allow true multithreading within a single Node.js process.
- 🧮 CPU-intensive operations
- 📊 Large data computations
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', msg => console.log('Message from worker:', msg));
} else {
parentPort.postMessage('Hello from Worker!');
}- ❓ What is the difference between
worker_threadsandcluster? - ❓ When should you use worker threads in a Node.js application?
Streams handle data chunk by chunk instead of loading everything into memory at once.
- 📖 Readable Stream (e.g.,
fs.createReadStream) - ✍️ Writable Stream (e.g.,
fs.createWriteStream) - 🔄 Duplex Stream (e.g., TCP Sockets)
- 🔧 Transform Stream (e.g.,
zlib.createGzip)
📖 Readable Stream:
const fs = require('fs');
const readStream = fs.createReadStream('file.txt');
readStream.on('data', chunk => console.log(chunk.toString()));✍️ Writable Stream:
const writeStream = fs.createWriteStream('output.txt');
writeStream.write('Hello, Stream!');🔧 Transform Stream (Compression):
const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
fs.createReadStream('input.txt').pipe(gzip).pipe(fs.createWriteStream('output.gz'));- ❓ What are the benefits of using Streams in Node.js?
- ❓ How does backpressure work in Streams?
- ⚡ Operational Errors (e.g., failed database connection)
- 🛠️ Programmer Errors (e.g.,
nullreference errors)
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
}
}
throw new AppError("Not Found", 404);- ❓ How do you handle asynchronous errors in Node.js?
- ❓ How does
process.on('uncaughtException')work?
- 🛡️ Use
helmetfor setting security headers:
const helmet = require('helmet');
app.use(helmet());- ✅ Validate user inputs to prevent SQL Injection and XSS.
- 🚫 Avoid using
eval()andexec(). - 🔑 Use environment variables securely.
- ❓ How can you prevent CSRF attacks in Node.js?
- ❓ Why is
eval()dangerous in Node.js?
Allows running external scripts or commands in a separate process.
const { exec } = require('child_process');
exec('ls', (err, stdout, stderr) => {
if (err) console.error(err);
console.log(stdout);
});- ❓ What is the difference between
execandspawnin Node.js? - ❓ How do you communicate between the main process and child processes?
- 🚀 Use Asynchronous APIs: Avoid blocking the event loop.
- 📊 Optimize Database Queries: Use indexing and pagination.
- 🗄️ Use Caching: Store frequent data in Redis or memory cache.
- 📦 Enable Compression: Use
zliborgzipfor smaller response payloads. - 🌐 Load Balancing with Clusters: Utilize multiple CPU cores.
const redis = require('redis');
const client = redis.createClient();
client.set("key", "value", 'EX', 3600);
client.get("key", (err, data) => console.log(data));- ❓ How does event loop optimization improve performance?
- ❓ How do you prevent memory leaks in Node.js?
- Introduction to NestJS
- Core Concepts
- Dependency Injection & Providers
- Module System (Import, Export, ForwardRef)
- Lifecycle Hooks
- Middleware, Guards, and Interceptors
- Exception Handling
- Circular Dependencies and Fixes
- Advanced Request Handling
- Database Integration with TypeORM
- Testing Strategies
- Deployment Best Practices
✅ A: NestJS is a progressive Node.js framework for building scalable server-side applications. It uses TypeScript by default and follows the modular architecture inspired by Angular.
✅ A:
- TypeScript support
- Dependency Injection
- Modular Architecture
- Built-in Middleware, Guards, Pipes, and Interceptors
- Support for WebSockets, GraphQL, and Microservices
- Easy Database Integration
- Scalable and Maintainable Codebase
✅ A: Controllers handle incoming HTTP requests and return responses.
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
getUsers() {
return this.userService.findAll();
}
}✅ A: Services contain business logic and can be injected into controllers.
@Injectable()
export class UserService {
findAll() {
return [{ id: 1, name: 'John Doe' }];
}
}✅ A: Dependency Injection is a design pattern where NestJS automatically provides instances of dependencies to classes that require them.
✅ A: Providers are classes that can be injected into other components using DI.
@Injectable()
export class UserService {}✅ A: Modules are used to group related components (controllers, providers, etc.) together.
@Module({
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}✅ A:
- If a module needs a service from another module, it must import that module.
- The other module must export the service so that it can be used.
@Module({
imports: [UserModule],
providers: [TaskService],
})
export class TaskModule {}✅ A: Lifecycle hooks allow developers to execute logic at specific points in a service's lifecycle.
| Hook | Description |
|---|---|
onModuleInit() |
Called when a module is initialized |
onModuleDestroy() |
Called when a module is destroyed |
beforeApplicationShutdown() |
Called before the app shuts down |
Example:
@Injectable()
export class UserService implements OnModuleInit {
onModuleInit() {
console.log('UserService initialized');
}
}With spec files (for testing) sh Copy Edit nest g module users nest g service users nest g controller users
without spec
nest g module users --no-spec nest g service users --no-spec nest g controller users --no-spec
This README provides a comprehensive deep dive into NestJS, covering fundamental concepts, dependency injection, module systems, lifecycle hooks, and more. 🚀 Let me know if you want further enhancements or additional sections!
This document covered advanced Node.js topics, including 🏭 clustering, 🧵 worker threads, 🔁 streams,