01. HTTP Server & Lifecycle
1. The Vanilla Mechanics
At the heart of every Node.js backend framework is the built-in http module. Node.js operates on an event-driven, non-blocking I/O model. When an HTTP request comes in, Node.js triggers a callback function.
Concept: The Event Loop & Streams
- Streams: Requests (
req) and responses (res) are streams. To read a body, you must manually listen todataandendevents. - Manual Control: You are responsible for setting status codes and headers manually.
The βRawβ Implementation (Example)
const http = require('http');
const server = http.createServer((req, res) => {
// Parsing the request body manually (Vanilla)
let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', () => {
console.log('Body received:', body);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from raw Node.js!');
});
});
server.listen(3000, () => console.log('Server running on port 3000'));Challenges:
- Boilerplate: Even simple body parsing requires several lines of stream logic.
- Scalability: Handling hundreds of routes with a single callback is unmaintainable.
- Error Handling: If an error occurs during stream processing, the server can crash without proper try/catch.
2. The NestJS Abstraction
NestJS (using Express or Fastify under the hood) abstracts the server creation process into a Module-based architecture.
Key Advantages:
NestFactory: A single entry point to bootstrap your application.- Modular Context: The entire app is a tree of modules that manage their own dependencies.
- Middleware Support: Automatically handles body parsing, URL encoding, and more.
The NestJS Implementation:
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
// This abstracts away the http.createServer() call
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();3. Engineering Labs
- Lab 1.1: Build a raw Node.js server that accepts a POST request and logs the JSON body without using any libraries.
- Lab 1.2: Boot a NestJS application and use the
@Post()decorator to receive the same JSON body. Observe how much boilerplate is removed.