-
Notifications
You must be signed in to change notification settings - Fork 15
/
devserver.mjs
44 lines (36 loc) · 1.27 KB
/
devserver.mjs
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
import http from 'http'
import url from 'url'
import fs from 'fs'
import path from 'path'
const port = 8080;
const baseDirectory = url.fileURLToPath(new URL('.', import.meta.url));
http
.createServer(function(request, response) {
try {
var requestUrl = url.parse(request.url);
// need to use path.normalize so people can't access directories underneath baseDirectory
var fsPath = path.join(baseDirectory, path.normalize(requestUrl.pathname));
console.log(fsPath);
// Force correct content-type for JavaScript
// This is a work-around for an issue where
// es6 modules have "" as content-type.
if (fsPath.endsWith('.js')) {
response.setHeader('content-type', 'text/javascript');
}
var fileStream = fs.createReadStream(fsPath);
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('Serving http://localhost:' + port + '/hamlet.html');