-
Notifications
You must be signed in to change notification settings - Fork 5
/
serve.js
49 lines (41 loc) · 1.62 KB
/
serve.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
import http from 'http';
import url from 'url';
import fs from 'fs';
import path from 'path';
const baseDirectory = path.dirname(url.fileURLToPath(import.meta.url));
const port = 4001;
http.createServer(function (request, response) {
try {
let requestUrl = url.parse(request.url)
// need to use path.normalize so people can't access directories underneath baseDirectory
let fsPath = baseDirectory + path.normalize(requestUrl.pathname)
if (fs.statSync(fsPath).isDirectory()) {
if (!fsPath.endsWith("/")) fsPath += "/";
fsPath += "index.html";
}
let options = {};
if (request.headers.range && request.headers.range.startsWith('bytes=')) {
let matches = /bytes=(\d*)-(\d*)/g.exec(request.headers.range);
options.start = parseInt(matches[1]);
options.end = parseInt(matches[2])+1;
response.setHeader('Content-Length', options.end - options.start);
}
if (fsPath.endsWith(".svg")) {
response.setHeader('Content-Type', "image/svg+xml");
}
let fileStream = fs.createReadStream(fsPath, options)
fileStream.pipe(response)
fileStream.on('open', function() {
response.writeHead(200)
})
fileStream.on('error',function(e) {
response.writeHead(404) // assume the file doesn't exist
response.end()
})
} catch(e) {
response.writeHead(500)
response.end() // end the response so browsers don't hang
console.log(e.stack)
}
}).listen(port)
console.log("listening on port " + port)