π· Introduction to Web Servers
A web server is a system that:
- Accepts requests from clients (usually web browsers),
- Processes those requests, and
- Sends back a response (such as HTML, JSON, or files).
In Node.js, we can create a web server using the built-in http
module without any external dependencies.
π§ Key Concepts
Term | Description |
---|---|
Server | A machine or application that provides services/data to the clients |
Client | The user or software (like a browser) that sends a request to the server |
HTTP | Protocol used for communication between client and server |
Request | Message sent by the client asking for data or action |
Response | Message sent back from server with data/status based on the request |
π§ How Node.js Creates a Web Server?
Node.js has a built-in module called http
that allows you to create a web server without any external tools.
β Basic Example:
const http = require('http');
// Create server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' }); // Set response header
res.end('Hello, MCA Students! Welcome to Node.js Web Server.');
});
// Server listens on port 3000
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
π Client-Server Communication Flow (Diagram Representation)
[Client (Browser)]
|
| HTTP Request (GET /index.html)
β
[Node.js Web Server]
|
| Processes the request
| Reads file / prepares data
β
[Sends Response] β HTTP 200 OK, HTML or JSON Content
β
[Client (renders result)]
π Handling Different Client Requests
Node.js can handle different routes based on the URL using conditional checks.
π Example:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Welcome to Home Page</h1>');
} else if (req.url === '/about') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>About Us</h1>');
} else {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
π§° Serving HTML, JSON, and Files
π Serve JSON:
if (req.url === '/api') {
const data = { name: "MCA Student", course: "Node.js" };
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
π Serve a file (HTML page):
const fs = require('fs');
if (req.url === '/home') {
fs.readFile('home.html', (err, data) => {
if (err) {
res.writeHead(500);
res.end('Error loading file');
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
}
});
}
βοΈ Role of Ports in Server Communication
- A port is a logical endpoint for communication.
- When you run
server.listen(3000)
, you’re saying: βThis Node.js server will listen for incoming client requests on port 3000.β
You can access it via:
π http://localhost:3000
π§ͺ Real-World Applications of Node.js Web Servers
Application Type | Description | Why Node.js? |
---|---|---|
REST APIs | Backend for mobile/web apps | Lightweight, fast, JSON-native |
Real-time apps (chat) | Live messaging, notifications | Event-driven architecture (Socket.io) |
File servers | Upload, download, manage files | Stream large files easily |
Proxy servers | Intermediary for other services | Non-blocking and fast |
Microservices | Independent backend services for large apps | Modular, scalable, and simple to deploy |
π Security & Performance Tips
- Use
https
instead ofhttp
for secure communication. - Implement rate-limiting and validation to prevent abuse.
- Use frameworks like Express.js for cleaner routing and middleware.
- Use clustering in Node.js to utilize multiple CPU cores.
π§βπ» Lab Activity Ideas
- β Create a basic web server using Node.js that returns plain text.
- π Build a simple REST API that returns JSON data.
- π Serve static HTML files from the server.
- π Implement routing for
/
,/about
, and/contact
. - π¦ Use Express.js to replicate the same server with simplified code.
π Summary
Concept | Key Takeaway |
---|---|
Node.js Web Server | Lightweight, event-driven server |
Client Request | Comes via HTTP from browser or other tools |
Server Response | Sends back data in HTML, JSON, or files |
Port Listening | Server listens on a port like 3000 |
Routing | Use conditional logic or Express routes |