-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttps-server.js
More file actions
61 lines (59 loc) · 2.28 KB
/
https-server.js
File metadata and controls
61 lines (59 loc) · 2.28 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
const https = require("https");
const express = require("express");
const cors = require("cors");
const filesystem = require("fs");
const acceptableHttpsPorts = [443, 8443, 8444];
function initHttpsServer() {
let httpsPortIndex = 0;
try {
const privateKey = filesystem.readFileSync("private.key", "utf8");
const certificate = filesystem.readFileSync("certificate.crt", "utf8");
let credentials;
if (filesystem.existsSync("ca_bundle.crt")) {
const ca = filesystem.readFileSync("ca_bundle.crt", "utf8");
credentials = { key: privateKey, cert: certificate, ca: ca };
} else {
credentials = { key: privateKey, cert: certificate };
}
const httpsApp = express();
httpsApp.use(cors());
httpsApp.use(express.text({ type: 'application/json' }));
const httpsServer = https.createServer(credentials, httpsApp);
startHttpsServer(acceptableHttpsPorts[0]);
function startHttpsServer(port) {
console.log(`Starting HTTPS server on port ${port}...`);
httpsServer.listen(port);
}
httpsServer.on('listening', () => {
const port = httpsServer.address().port;
console.log(`Https server is running at https://localhost:${port}`);
});
httpsServer.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.log(`Port ${e.port} is already in use.`);
changePort();
} else if (e.code === 'EACCES') {
console.log(`Permission denied to use HTTPS port ${e.port}`);
changePort();
} else {
console.log(`Error with HTTPS server:`, e.message);
}
});
function changePort() {
httpsPortIndex++;
if (httpsPortIndex < acceptableHttpsPorts.length) {
const nextPort = acceptableHttpsPorts[httpsPortIndex];
console.log(`Trying next port: ${nextPort}`);
startHttpsServer(nextPort);
} else {
console.error("No more acceptable HTTPS ports available.");
}
}
return httpsApp
} catch (e) {
console.log(`HTTPS error: ${e}`);
}
}
module.exports = {
initHttpsServer
}