Building an Http Server With Node
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
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);
}