BUILDING AN HTTP SERVER WITH NODE.
JS
1. Introduction
This report documents the steps to create a basic HTTP server using Node.js. The server
handles multiple content types (HTML, JSON, XML, CSV) and serves static files.
2. Project Setup
2.1 Directory Structure
http-server/
├── server.js # Main server script
├── package.json # Node.js project configuration
└── public/ # Static files
├── index.html # Homepage
└── about.html # About page
2.2 Initialize Node.js Project
npm init -y
3. Implementation
3.1 Server Code (server.js)
javascript
Copy
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
serveHTML(res, 'index.html');
} else if (req.url === '/json' && req.method === 'GET') {
serveJSON(res);
} else if (req.url === '/xml' && req.method === 'GET') {
serveXML(res);
} else if (req.url === '/csv' && req.method === 'GET') {
serveCSV(res);
} else if (req.url === '/about' && req.method === 'GET') {
serveHTML(res, 'about.html');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
function serveJSON(res) {
const data = { name: "John Doe", email: "[email protected]" };
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
function serveXML(res) {
constxml `<user><name>John Doe</name><email>[email protected]</email></user>`;
res.writeHead(200, { 'Content-Type': 'application/xml' });
res.end(xml);
}
function serveCSV(res) {
const csv = "name,email\nJohn Doe,[email protected]";
res.writeHead(200, {
'Content-Type': 'text/csv',
'Content-Disposition': 'attachment; filename=data.csv'
});
res.end(csv);
}
function serveHTML(res, filename) {
const filePath = path.join(__dirname, 'public', filename);
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end("Error loading HTML file");
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
}
});
}
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
3.2 HTML Files
public/index.html
html
Copy
<!DOCTYPE html>
<html>
<head>
<title>HTTP Server</title>
</head>
<body>
<h1>Welcome to the HTTP Server!</h1>
<p>Try these endpoints:</p>
<ul>
<li><a href="/json">/json</a> (JSON response)</li>
<li><a href="/xml">/xml</a> (XML response)</li>
<li><a href="/csv">/csv</a> (CSV download)</li>
<li><a href="/about">/about</a> (About page)</li>
</ul>
</body>
</html>
Run HTML
public/about.html
html
Copy
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<h1>About This Server</h1>
<p>This is a basic HTTP server built with Node.js.</p>
<a href="/">Back to Home</a>
</body>
</html>
Run HTML
4. Running the Server
4.1 Start the Server
node server.js
Expected Output:
Server running on http://localhost:3000
Output :
5. Conclusion
The project demonstrates a functional HTTP server with multi-format responses.