-
Notifications
You must be signed in to change notification settings - Fork 5
/
dev-server.js
78 lines (62 loc) · 1.66 KB
/
dev-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
import * as http from "http";
import * as tls from "tls";
import split from "split";
import { Server as StaticServer } from "node-static";
import { WebSocketServer } from "ws";
const WS_BAD_GATEWAY = 1014;
const usage = `usage: [options...] [host]
Starts an HTTP server delivering static files. If [host] is specified, the
server will proxy WebSocket connections to the specified remote IRC server.
Options:
-p <port> Listening port (default: 8080)
-h Show help message
`;
let localPort = 8080;
let remoteHost;
let remotePort = 6697;
let args = process.argv.slice(2);
while (args.length > 0 && args[0].startsWith("-")) {
switch (args[0]) {
case "-p":
localPort = parseInt(args[1], 10);
args = args.slice(2);
break;
default:
console.log(usage);
process.exit(args[0] === "-h" ? 0 : 1);
}
}
remoteHost = args[0];
let staticServer = new StaticServer(".");
let server = http.createServer((req, res) => {
staticServer.serve(req, res);
});
if (remoteHost) {
let wsServer = new WebSocketServer({ server });
wsServer.on("connection", (ws) => {
let client = tls.connect(remotePort, remoteHost, {
ALPNProtocols: ["irc"],
});
ws.on("message", (data) => {
client.write(data.toString() + "\r\n");
});
ws.on("close", () => {
client.destroy();
});
client.pipe(split()).on("data", (data) => {
ws.send(data.toString());
});
client.on("end", () => {
ws.close();
});
client.on("error", () => {
ws.close(WS_BAD_GATEWAY);
});
});
}
server.listen(localPort, "localhost");
let msg = "HTTP server listening on http://localhost:" + localPort;
if (remoteHost) {
msg += " and proxying WebSockets to " + remoteHost;
}
console.log(msg);