Skip to content

Nodejs-Webserver – Server and Clients

πŸ”· 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

TermDescription
ServerA machine or application that provides services/data to the clients
ClientThe user or software (like a browser) that sends a request to the server
HTTPProtocol used for communication between client and server
RequestMessage sent by the client asking for data or action
ResponseMessage 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 TypeDescriptionWhy Node.js?
REST APIsBackend for mobile/web appsLightweight, fast, JSON-native
Real-time apps (chat)Live messaging, notificationsEvent-driven architecture (Socket.io)
File serversUpload, download, manage filesStream large files easily
Proxy serversIntermediary for other servicesNon-blocking and fast
MicroservicesIndependent backend services for large appsModular, scalable, and simple to deploy

πŸ”’ Security & Performance Tips

  • Use https instead of http 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

  1. βœ… Create a basic web server using Node.js that returns plain text.
  2. πŸ“„ Build a simple REST API that returns JSON data.
  3. 🌐 Serve static HTML files from the server.
  4. πŸ” Implement routing for /, /about, and /contact.
  5. πŸ“¦ Use Express.js to replicate the same server with simplified code.

πŸ“ Summary

ConceptKey Takeaway
Node.js Web ServerLightweight, event-driven server
Client RequestComes via HTTP from browser or other tools
Server ResponseSends back data in HTML, JSON, or files
Port ListeningServer listens on a port like 3000
RoutingUse conditional logic or Express routes