-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserve.js
More file actions
90 lines (80 loc) · 2.48 KB
/
Copy pathserve.js
File metadata and controls
90 lines (80 loc) · 2.48 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
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = parseInt(process.env.PORT || "3001", 10);
const ROOT = process.argv[2] || ".";
const MIME_TYPES = {
".html": "text/html",
".js": "application/javascript",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".bam": "application/octet-stream",
".bai": "application/octet-stream",
".arrow": "application/octet-stream",
".wasm": "application/wasm",
};
function serveFile(req, res, filePath, stats) {
const mimeType = MIME_TYPES[path.extname(filePath).toLowerCase()] || "application/octet-stream";
const fileSize = stats.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
if (start >= fileSize) {
res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
res.end();
return;
}
const chunkSize = end - start + 1;
res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
"Accept-Ranges": "bytes",
"Content-Length": chunkSize,
"Content-Type": mimeType,
});
fs.createReadStream(filePath, { start, end }).pipe(res);
} else {
res.writeHead(200, {
"Content-Length": fileSize,
"Content-Type": mimeType,
"Accept-Ranges": "bytes",
});
fs.createReadStream(filePath).pipe(res);
}
}
const server = http.createServer((req, res) => {
let filePath = path.join(ROOT, path.normalize(new URL(req.url, "http://localhost").pathname));
if (filePath.endsWith("/")) {
filePath = path.join(filePath, "index.html");
}
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
const hasExtension = path.extname(filePath) !== "";
if (hasExtension) {
res.writeHead(404);
res.end("Not Found");
return;
}
filePath = path.join(ROOT, "index.html");
fs.stat(filePath, (err2, stats2) => {
if (err2) {
res.writeHead(404);
res.end("Not Found");
return;
}
serveFile(req, res, filePath, stats2);
});
return;
}
serveFile(req, res, filePath, stats);
});
});
server.listen(PORT, () => {
console.log(`Serving ${path.resolve(ROOT)} on http://localhost:${PORT}`);
console.log("Press Ctrl+C to stop the server.");
});