-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
90 lines (70 loc) · 2.66 KB
/
Copy pathserver.js
File metadata and controls
90 lines (70 loc) · 2.66 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
88
89
#!/bin/env node
// General static file server for Node.js
//
// Supports
// - 301 Redirects
// - Content-Type headers for js, css, and manifest files
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
program = require('commander');
program
.option('-p, --port <n>', 'Port to run server on.')
.option('-h, --host [value]', 'Bind address or host.')
.option('-d, --domain', 'Cannonical host. All requests are rewritten to this URL')
.parse(process.argv);
var port = program.port || process.env.PORT || process.env.OPENSHIFT_INTERNAL_PORT || process.env.VCAP_APP_PORT || 8888,
host = program.host || process.env.OPENSHIFT_INTERNAL_IP || "0.0.0.0";
var REDIRECT_PROTOCOL = "http://"
REDIRECT_HOST = program.domain || process.env.DOMAIN || (host + ":" + port);
http.createServer(function(request, response) {
var hostname = request.headers.host;
if (hostname !== REDIRECT_HOST) {
response.writeHead(301, {
'Location': REDIRECT_PROTOCOL + REDIRECT_HOST + request.url,
'Expires': (new Date).toGMTString()
});
response.end();
return;
}
var uri = url.parse(request.url).pathname,
filename = path.join(__dirname, "www", uri);
fs.exists(filename, function(exists) {
if(!exists) {
filename = path.join(__dirname, "index.html");
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found :( Sorry.\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
var opts;
if (filename.indexOf(".js") > 0) {
opts = {"Content-Type": "application/x-javascript"};
} else if (filename.indexOf(".css") > 0) {
opts = {"Content-Type": "text/css"};
} else if (filename.indexOf(".manifest") > 0) {
opts = {
// never cache a manifest file
"Cache-Control": "no-cache, must-revalidate",
"Expires": "Sat, 26 Jul 1997 05:00:00 GMT",
"Content-Type": "text/cache-manifest"
};
} else if (filename.indexOf(".webapp") > 0) {
opts = {"Content-Type": "application/x-web-app-manifest+json"};
}
response.writeHead(200, opts);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10), host);
console.log("FlipClock running at\n => http://" + REDIRECT_HOST + "/\nCTRL + C to shutdown");