-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathserve.js
More file actions
55 lines (47 loc) 路 1.83 KB
/
Copy pathserve.js
File metadata and controls
55 lines (47 loc) 路 1.83 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
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 = 3367;
http.createServer(function (request, response) {
try {
const url = new URL(request.url, 'http://localhost');
const safePath = path.normalize(url.pathname);
let fsPath = path.join(baseDirectory, 'docs', safePath);
if (!fsPath.startsWith(path.join(baseDirectory, 'docs'))) {
throw new Error('Invalid path');
}
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);
}
// set MIME types
if (fsPath.endsWith(".svg")) {
response.setHeader('Content-Type', "image/svg+xml");
} else if (fsPath.endsWith(".js")) {
response.setHeader('Content-Type', "text/javascript");
}
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)