-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPFileServer.js
More file actions
87 lines (71 loc) · 2.36 KB
/
Copy pathHTTPFileServer.js
File metadata and controls
87 lines (71 loc) · 2.36 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
var http = require('http');
var fs = require('fs');
var url = require('url');
/*HTTP MIME resolver*/
var MIME = {
js:'application/javascript',
html:'text/html',
css:'text/css',
json:'application/json',
woff:'application/font-woff',
woff2:'application/font-woff2',
svg:'image/svg+xml',
ttf:'application/x-font-ttf',
default:'',
getMime:function(file){
let _pathparts = file.split('.');
let extension = _pathparts[_pathparts.length-1];
if(MIME[extension.toLowerCase()]){
return MIME[extension.toLowerCase()];
}else{
return MIME.default;
}
}
}
var StaticFileAccess = function(root){
this.cache = {};
this.get = function(path, callback, onerror){
if(this.cache[path]){
callback(cache[path]);
return;
}
let mime = MIME.getMime(path);
fs.readFile(root+'/'+path, 'utf8', function(err, data){
if(err){onerror(err);return;}
let file = {
data:data,
mime:mime
};
callback(file);
}.bind(this));
};
};
var HTTPFileServer = function(port, root, onStarted){
var files = new StaticFileAccess(root);
this.handleRequest = function(request, response){
try{
let path = url.parse(request.url).pathname;
if(!this.acceptUrl(url.parse(request.url))) throw 'Forbidden url.';
if(path=='/')path='index.html';
console.log(request.method, path);
files.get(path, function(file){
console.log(request.method, path, 'RESOLVED', file.mime);
response.setHeader('Content-Type', file.mime);
response.end(file.data);
}, function(err){
response.statusCode = 404; response.end("Not found.");
});
}catch(_e){
response.statusCode=500;response.end(_e);
}
}.bind(this);
this.server = http.createServer(this.handleRequest.bind(this));
this.server.listen(port, function(){
if(onStarted){onStarted(this.server);}
}.bind(this));
this.acceptUrl = function(url){
if(url.pathname.indexOf('..')>-1)return false;
return true;
}
}
module.exports = HTTPFileServer;