-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilt-in-http.js
56 lines (50 loc) · 1.43 KB
/
built-in-http.js
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
const http = require("node:http");
const fs = require("node:fs");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Home page");
} else if (req.url === "/about") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("About Page");
} else if (req.url === "/api") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
firstName: "Bruce",
lastName: "Wayne",
})
);
} else {
res.writeHead(404);
res.end("Page not found");
}
});
/** HTML template
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
const name = "Vishwas";
let html = fs.readFileSync(`${__dirname}/index.html`, "utf8");
html = html.replace("{{name}}", name);
res.end(html);
});
*/
/** HTML response
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
fs.createReadStream(__dirname + "/index.html").pipe(res);
});
*/
/** JSON response
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
const superHero = {
firstName: "Bruce",
lastName: "Wayne",
};
res.end(superHero);
});
*/
server.listen(3000, () => {
console.log("Server running on port 3000");
});