-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
executable file
·93 lines (78 loc) · 1.89 KB
/
server.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
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
91
92
#!/usr/bin/env node
var port = 8000;
var http = require('http');
var fs = require('fs');
var server = http.createServer();
var publicDirectory = '.';
var mime;
try{
mime = require('mime');
}
catch(e){
console.error('mime not installed please run: npm install mime');
}
server.on('request', function(request, response){
var r = require('url').parse(request.url, true);
var pathname = r.pathname;
var query = r.query;
try{
// proxying ?
if ( pathname == "/proxy" ) {
console.log("acting as a proxy...");
var options = {}
console.log("url: " + r.query.url);
resource = require('url').parse(r.query.url, true);
options = {
hostname: resource.hostname,
port: resource.port,
path: resource.path,
headers: {
"Authorization": request.headers['authorization'],
"Content-Encoding": request.headers['content-encoding']
},
method: 'GET' //r.query.method
};
var proxy = http.request(options, function (res) {
res.pipe(response, {
end: true
});
});
request.pipe(proxy, {
end: true
});
} else {
var filePath;
if (pathname == "/") {
filePath = "./index.html";
} else {
filePath = '.' + pathname;
}
if ( fs.existsSync(filePath) ){
response.writeHead(200, {
'content-type': mime.lookup(filePath),
'cache-control': 'no-cache'
});
response.write(fs.readFileSync(filePath));
response.end();
}
else{
response.writeHead(404);
response.write("Not found, sorry :-( Happy 404 ;-)")
response.end();
}
if (pathname != '/favicon.ico') {
console.log(pathname);
}
response.writeHead(200, {'content-type': 'text/plain'});
response.end();
return;
}
}
catch(e){
console.log("Exception catched: " + e);
response.writeHead(500);
response.end();
}
});
server.listen(port);
console.log('Server running on port ' + port);