-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpushstate-https-server.js
More file actions
76 lines (66 loc) · 1.73 KB
/
pushstate-https-server.js
File metadata and controls
76 lines (66 loc) · 1.73 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
'use strict';
let express = require('express'),
path = require('path'),
_ = require('lodash'),
https = require('https'),
http = require('http'),
fs = require('fs');
let pushstateServer = {
server: null,
address: null,
port: null,
createServer: function (options) {
this.address = options.address || '127.0.0.1';
this.port = options.port || 8080;
let rootDir = options.root;
let dirs = options.dirs;
let pkFile = options.keyPath;
let certFile = options.certPath;
let app = express();
let getPath = function(url, type) {
let paramsRemoved = _.first(url.split('?'));
let filepath = _.last(paramsRemoved.split(type));
return path.resolve(rootDir + '/' + type + filepath);
};
app.get('*', function(request, response){
let url = request.url;
let lastItem = _.last(url.split('/'));
if (_.isEmpty(lastItem)) {
response.sendFile(path.resolve(rootDir + '/index.html'));
}
else {
var responded = false;
for (var i = 0; i < _.size(dirs); i++) {
let dir = dirs[i];
let regex = new RegExp('.*/' + dir + '/.*')
if (url.match(regex)) {
response.sendFile(getPath(url, dir));
responded = true;
break;
}
}
if (!responded) {
response.sendFile(path.resolve(rootDir + '/index.html'));
}
}
});
if (options.https) {
let sslInfo = {
key: fs.readFileSync(pkFile).toString(),
cert: fs.readFileSync(certFile).toString()
};
this.server = https.createServer(sslInfo, app);
}
else {
this.server = http.createServer(app);
}
return this;
},
start: function (callback) {
this.server.listen(this.port, this.address, callback);
},
stop: function () {
this.server.close();
}
};
module.exports = pushstateServer;