-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp-server.js
More file actions
50 lines (45 loc) · 1.53 KB
/
http-server.js
File metadata and controls
50 lines (45 loc) · 1.53 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
const express = require("express");
const cors = require("cors");
const http = require("http");
const acceptableHttpPorts = [80, 8080, 8000];
function initHttpServer() {
let httpPortIndex = 0;
const httpApp = express();
httpApp.use(cors());
httpApp.use(express.text({ type: 'application/json' }));
const httpServer = http.createServer(httpApp);
startHttpServer(acceptableHttpPorts[0]);
function startHttpServer(port) {
console.log(`Starting HTTP server on port ${port}...`);
httpServer.listen(port);
}
httpServer.on('listening', () => {
const port = httpServer.address().port;
console.log(`Http server is running at http://localhost:${port}`);
});
httpServer.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 HTTP port ${e.port}`)
changePort();
} else {
console.log(`Error with HTTP server:`, e.message);
}
});
function changePort() {
httpPortIndex++;
if (httpPortIndex < acceptableHttpPorts.length) {
const nextPort = acceptableHttpPorts[httpPortIndex];
console.log(`Trying next port: ${nextPort}`);
startHttpServer(nextPort);
} else {
console.error("No more acceptable HTTP ports available.");
}
}
return httpApp
}
module.exports = {
initHttpServer
}