Server in Node.js
What is a Server?
The term "server" is used loosely in the tech industry and can refer to both hardware and software:
Hardware Server
- Physical Machine: A computer with CPU, RAM, storage, and network capabilities
- Operating System: Runs Linux, Windows, or other OS
- Always On: 24/7 uptime with power backups
- High-Speed Internet: Dedicated IP addresses
- Examples: AWS EC2 instances, data center machines
Software Server
- Application: A program that handles client requests
- HTTP Server: Serves web content using HTTP protocol
- Database Server: Manages database operations
- File Server: Handles file storage and retrieval
Why Use Cloud Servers (AWS, etc.)?
Instead of using your laptop as a server, cloud providers offer:
- Scalability: Easy to increase RAM, storage, processing power
- Reliability: 24/7 uptime, no power outages
- Dedicated IP: Static IP addresses
- Managed Infrastructure: No hardware maintenance
- Global Reach: Multiple data centers worldwide
Client-Server Architecture
Basic Concepts
- Client: The entity requesting data (browser, mobile app, etc.)
- Server: The entity providing data and services
- Request: Client asking for resources
- Response: Server sending back data
How It Works
- Client opens a socket connection to server
- Client sends HTTP request
- Server processes the request
- Server sends HTTP response
- Socket connection is closed
Multiple Clients
- Multiple clients can connect simultaneously
- Each client creates its own socket connection
- Server handles concurrent requests
- Connections are opened, data is transferred, then closed
Understanding Protocols
What is a Protocol?
A protocol is a set of rules that computers follow to communicate with each other. Think of it like a common language that both computers understand.
Key Protocols
TCP/IP (Transmission Control Protocol/Internet Protocol)
- Purpose: Governs how data is transmitted over the internet
- Features: Reliable, connection-oriented, error-checking
- Data Transmission: Sends data in small packets, not all at once
- When Used:
- Every internet communication uses TCP/IP as the foundation
- When establishing socket connections between client and server
- Underlying protocol for all web traffic
- File transfers, email, web browsing all rely on TCP/IP
- How It Works:
- Breaks data into small packets for transmission
- Each packet is numbered and can take different routes
- Packets are reassembled at the destination
- Provides error checking and retransmission of lost packets
HTTP (Hypertext Transfer Protocol)
- Purpose: Rules for web communication
- Usage: Web browsers and web servers
- Data Types: HTML, JSON, plain text, images
- When Used:
- Loading websites in browsers (http://example.com (opens in a new tab))
- Making API calls from frontend to backend
- Sending form data from web pages
- Downloading web resources (CSS, JS, images)
- RESTful API communications
- Common HTTP Methods:
GET
: Retrieve data from serverPOST
: Send data to serverPUT
: Update existing dataDELETE
: Remove data
- Example Use Cases:
GET http://api.example.com/users // Get list of users POST http://api.example.com/users // Create new user PUT http://api.example.com/users/1 // Update user with ID 1 DELETE http://api.example.com/users/1 // Delete user with ID 1
Other Protocols
FTP (File Transfer Protocol)
- Purpose: Specialized protocol for transferring files
- When Used:
- Uploading websites to web servers
- Downloading large files from servers
- Backing up files to remote servers
- Sharing files between computers
- Characteristics:
- Separate control and data connections
- Supports authentication (username/password)
- Can handle large file transfers efficiently
- Example:
ftp://files.example.com/documents/report.pdf
SMTP (Simple Mail Transfer Protocol)
- Purpose: Sending emails between servers
- When Used:
- Sending emails from email clients (Gmail, Outlook)
- Server-to-server email delivery
- Automated email notifications from applications
- Newsletter and marketing email systems
- How It Works:
- Client connects to SMTP server (usually port 25, 587, or 465)
- Authenticates with credentials
- Sends email data (headers, body, attachments)
- Server forwards email to recipient's mail server
DNS (Domain Name System)
- Purpose: Translates domain names to IP addresses
- When Used:
- Every time you type a URL in browser
- Before any HTTP request is made
- Email routing (MX records)
- Service discovery in microservices
- Process:
- Browser asks DNS: "What's the IP for google.com?"
- DNS responds: "It's 172.217.164.110"
- Browser connects to that IP address
- HTTP request is sent to the server
Protocol Stack in Action
When you visit a website, multiple protocols work together:
1. DNS Protocol: Resolve domain name to IP address
2. TCP/IP: Establish connection to server
3. HTTP: Request and receive web content
4. (Optional) SMTP: If contact form sends email
5. (Optional) FTP: If downloading files
Real-World Protocol Usage Examples
Example 1: Loading a Website
User types: https://www.example.com
Step 1: DNS Protocol
- Browser asks DNS server: "What's the IP for www.example.com?"
- DNS responds: "It's 93.184.216.34"
Step 2: TCP/IP Protocol
- Browser establishes TCP connection to 93.184.216.34:443
- Three-way handshake completed
Step 3: HTTP Protocol
- Browser sends: GET / HTTP/1.1 Host: www.example.com
- Server responds with HTML content
- Additional HTTP requests for CSS, JS, images
Example 2: Sending Contact Form
User submits contact form on website
Step 1: HTTP Protocol
- Browser sends POST request with form data
- Server receives and processes form data
Step 2: SMTP Protocol (Server-side)
- Server connects to SMTP server
- Sends email notification to admin
- Email delivered via SMTP chain
Example 3: File Upload/Download
User uploads file to server
Option A: HTTP Protocol
- File sent via HTTP POST with multipart/form-data
- Good for smaller files through web interface
Option B: FTP Protocol
- Direct FTP connection for large files
- More efficient for bulk file operations
- Often used by developers and content managers
Protocol Selection Guidelines
Use HTTP when:
- Building web applications
- Creating REST APIs
- Sending small to medium files
- Need simple request-response communication
Use FTP when:
- Transferring large files
- Bulk file operations
- Need reliable file transfer with resume capability
- Managing website files on servers
Use SMTP when:
- Sending emails from applications
- Building email notification systems
- Creating automated email workflows
TCP/IP is always used as:
- The underlying transport for all above protocols
- Foundation for reliable internet communication
IP Addresses and Domain Names
IP Addresses
- Definition: Unique numerical address for each device on the internet
- Format: Example: 192.168.1.1
- Purpose: Computers use IP addresses to locate each other
Domain Names
- Definition: Human-readable names that map to IP addresses
- Examples: google.com, namastedev.com
- Purpose: Easier for humans to remember than IP addresses
DNS (Domain Name System)
- Function: Maps domain names to IP addresses
- Process: When you type "google.com", DNS finds the corresponding IP
- Hierarchy: Reads domain from right to left (.com → google → www)
Ports and Multiple Servers
What is a Port?
- Definition: A numerical identifier (usually 4 digits) for specific services
- Purpose: Allows multiple applications to run on the same server
- Format: IP:Port (e.g., 192.168.1.1:3000)
Common Ports
- 80: HTTP (default web traffic)
- 443: HTTPS (secure web traffic)
- 3000: Common for development servers
- 8080: Alternative HTTP port
Multiple Servers on Same Machine
Server Machine (IP: 192.168.1.1)
├── Web Server (Port 3000)
├── API Server (Port 3001)
├── Database Server (Port 5432)
└── Email Server (Port 25)
Socket vs WebSocket
Regular Socket
- Lifecycle: Open → Send Request → Receive Response → Close
- Usage: Traditional web browsing
- Efficiency: New connection for each request
WebSocket
- Lifecycle: Open → Keep Connection Alive → Bidirectional Communication
- Usage: Real-time applications (chat, gaming, live updates)
- Efficiency: Persistent connection, lower overhead
Creating Your First Server
Basic HTTP Server
const http = require("node:http");
const server = http.createServer((req, res) => {
res.end("Hello World!");
});
server.listen(7777, () => {
console.log("Server running on port 7777");
});
Handling Different Routes
const http = require("node:http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.end("Welcome to the homepage!");
} else if (req.url === "/about") {
res.end("About page");
} else {
res.end("404 - Page not found");
}
});
server.listen(7777);
Testing Your Server
- Run:
node server.js
- Open browser:
http://localhost:7777
- Try different URLs:
http://localhost:7777/about
Data Transmission
How Data Travels
- Packets: Data is broken into small chunks (packets)
- Streaming: Data flows as a continuous stream
- Buffers: Temporary storage for incoming data chunks
- Reassembly: Packets are reassembled at destination
Streams and Buffers in Node.js
- Streams: Continuous flow of data
- Buffers: Handle binary data efficiently
- Event-driven: Process data as it arrives
Express Framework
Why Express?
The native HTTP module is powerful but low-level. Express provides:
- Easier Routing: Simple URL pattern matching
- Middleware: Reusable request processing functions
- Built-in Features: Static file serving, template engines
- Community: Large ecosystem of plugins
Express vs Native HTTP
// Native HTTP (Complex)
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/users" && req.method === "GET") {
// Handle GET users
} else if (req.url === "/users" && req.method === "POST") {
// Handle POST users
}
// ... lots of if-else statements
});
// Express (Simple)
const express = require("express");
const app = express();
app.get("/users", (req, res) => {
// Handle GET users
});
app.post("/users", (req, res) => {
// Handle POST users
});
MEAN Stack
Components
- M: MongoDB (Database)
- E: Express.js (Web Framework)
- A: Angular (Frontend - can be React)
- N: Node.js (Runtime Environment)
How They Work Together
- Frontend (Angular/React): User interface
- Backend (Node.js + Express): Server logic and APIs
- Database (MongoDB): Data storage
- Communication: HTTP requests between frontend and backend
Key Takeaways
- Server Context: Always understand if "server" refers to hardware or software
- Protocols: Different rules for different types of communication
- Ports: Allow multiple services on the same machine
- Sockets: Connections between clients and servers
- Express: Preferred framework for Node.js web applications
- Real-world: Multiple servers often work together in production
Best Practices
- Use Express: Don't build with native HTTP module for complex applications
- Handle Errors: Always implement error handling
- Environment Variables: Use different ports for different environments
- Logging: Log requests and errors for debugging
- Security: Validate input, use HTTPS in production
Common Vocabulary
- Listen: Server waiting for incoming requests
- Incoming Requests: Client requests arriving at server
- Socket Connection: Communication channel between client and server
- HTTP Server: Server that handles HTTP protocol
- Port: Numerical identifier for services
- Instance: A running copy of a server/application
- Deploy: Put your application on a server
- Hosting: Making your application available on the internet
This guide covers the fundamental concepts of servers and web development with Node.js. Practice by creating your own servers and experimenting with different routes and responses!