-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-http-server.js
More file actions
184 lines (164 loc) Β· 6.22 KB
/
basic-http-server.js
File metadata and controls
184 lines (164 loc) Β· 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// ============================================
// LECTURE 13-16: HTTP Module & Creating Endpoints
// ============================================
// This demonstrates creating a server using native HTTP module
// Before frameworks like Express, this is how we created servers
const http = require("http"); // Built-in Node.js module
const fs = require("fs"); // File System module
const path = require("path"); // Path module
const url = require("url"); // URL parsing module
const PORT = process.env.HTTP_PORT || 4000;
// ============================================
// LECTURE 21-24: Request Handler Function
// ============================================
const server = http.createServer((req, res) => {
// Parse URL with query parameters
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
const query = parsedUrl.query;
// ============================================
// Route 1: Home Page (GET method)
// ============================================
if (req.method === "GET" && pathname === "/") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(`
<html>
<head>
<title>Native HTTP Server</title>
<style>
body { font-family: Arial; max-width: 800px; margin: 50px auto; padding: 20px; }
h1 { color: #333; }
.endpoint { background: #f4f4f4; padding: 10px; margin: 10px 0; border-radius: 5px; }
code { background: #333; color: #fff; padding: 2px 6px; border-radius: 3px; }
</style>
</head>
<body>
<h1>π Native HTTP Module Server</h1>
<p>This server demonstrates HTTP module without any framework</p>
<h2>Available Endpoints:</h2>
<div class="endpoint">
<strong>GET /api/info</strong> - Server information
</div>
<div class="endpoint">
<strong>GET /api/data?name=value</strong> - Query parameters demo
</div>
<div class="endpoint">
<strong>POST /api/submit</strong> - POST request handling
</div>
<div class="endpoint">
<strong>GET /file/sample.txt</strong> - File streaming demo
</div>
</body>
</html>
`);
return;
}
// ============================================
// Route 2: API Info (GET with JSON response)
// Response Methods: res.writeHead(), res.end()
// ============================================
if (req.method === "GET" && pathname === "/api/info") {
const payload = {
topic: "Node.js HTTP module endpoint demo",
evaluation: "Backend first evaluation",
module: "Native HTTP (no framework)",
time: new Date().toISOString(),
port: PORT
};
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(payload, null, 2));
return;
}
// ============================================
// Route 3: Query Parameters Demo
// LECTURE 21-24: Route parameters handling
// ============================================
if (req.method === "GET" && pathname === "/api/data") {
const response = {
message: "Query parameters received",
queryParams: query,
example: "Try: /api/data?name=John&age=25"
};
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(response, null, 2));
return;
}
// ============================================
// Route 4: POST Request Handling
// LECTURE 13-16: Handling request body
// ============================================
if (req.method === "POST" && pathname === "/api/submit") {
let body = "";
// Collect data chunks
req.on("data", (chunk) => {
body += chunk.toString();
});
// Process complete data
req.on("end", () => {
try {
const data = JSON.parse(body);
const response = {
success: true,
message: "Data received successfully",
receivedData: data,
timestamp: new Date().toISOString()
};
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(response, null, 2));
} catch (error) {
// Exception handling
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Invalid JSON format" }));
}
});
return;
}
// ============================================
// Route 5: File Streaming Demo
// LECTURE 21-24: Handling static pages with file stream
// ============================================
if (req.method === "GET" && pathname.startsWith("/file/")) {
const fileName = pathname.split("/file/")[1];
const filePath = path.join(__dirname, "data", fileName);
// Check if file exists
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "File not found" }));
return;
}
// Stream file to response
const readStream = fs.createReadStream(filePath);
res.writeHead(200, { "Content-Type": "text/plain" });
// Pipe file stream to response
readStream.pipe(res);
// Handle stream errors
readStream.on("error", (streamErr) => {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Error reading file" }));
});
});
return;
}
// ============================================
// 404 - Route Not Found (Exception Handling)
// LECTURE 21-24: Handling exceptions
// ============================================
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({
error: "Route not found in native HTTP server",
requestedPath: pathname,
method: req.method
}));
});
// ============================================
// Start Server and Listen on Port
// ============================================
server.listen(PORT, () => {
console.log(`\n${"=".repeat(50)}`);
console.log(`π Native HTTP Server Running`);
console.log(`${"=".repeat(50)}`);
console.log(`π URL: http://localhost:${PORT}`);
console.log(`π This demonstrates Lectures 13-16 & 21-24`);
console.log(`${"=".repeat(50)}\n`);
});