forked from phil-giambra/code_bits
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_basic_server.js
More file actions
80 lines (68 loc) · 2.56 KB
/
http_basic_server.js
File metadata and controls
80 lines (68 loc) · 2.56 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
const fs = require('fs');
const http = require('http');
let http_root = "./http_basic_root"
let http_default_file = "index.html"
let http_port = 9191
const requestListener = function (req, res) {
let notFound = function() {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404 Not Found\n");
res.end();
}
//console.log("http request", res);
let url = req.url
if ( url === "/" ) url += http_default_file
let method = req.method
let cont_type = req.headers.accept.split(",")[0]
console.log("http request for ", url , cont_type)
// you may have to add options to this switch depending on the
// Content-Type of the files that you serve
switch (cont_type) {
case "*/*":
let ending = url
if ( ending.split(".").pop() === "js" ) {
res.writeHead(200, { "Content-Type": "text/javascript" });
}
if ( ending.split(".").pop() === "json" ) {
res.writeHead(200, { "Content-Type": "text/json" });
}
if ( ending.split(".").pop() === "ttf" ) {
res.writeHead(200, { "Content-Type": "font/ttf" });
}
//
break;
case "image/webp":
res.writeHead(200, { "Content-Type": "image/webp" });
break;
case "text/css":
res.writeHead(200, { "Content-Type": "text/css" });
break;
case "text/html":
res.writeHead(200, { "Content-Type": "text/html" });
break;
case "image/avif":
res.writeHead(200, { "Content-Type": "image/avif" });
break;
default:
// unknown Content-Type send 404 not found responce
notFound()
return;
}
// This line opens the file as a readable stream
let readStream = fs.createReadStream( http_root + url );
// This will wait until we know the readable stream is actually valid before piping
readStream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
});
// This catches any errors that happen while creating the readable stream (usually invalid names)
readStream.on('error', function(err) {
//console.log(err);
console.log("readstream error", cont_type, url);
notFound()
return;
});
}
const server = http.createServer(requestListener);
server.listen(http_port, "0.0.0.0");
console.log(`HTTP Server started on port ${http_port} `);