-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
54 lines (47 loc) · 1.53 KB
/
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
import { listenAndServe } from "https://deno.land/std@0.67.0/http/server.ts";
import { serveFile } from "https://deno.land/std@0.67.0/http/file_server.ts";
import { acceptWebSocket, acceptable } from "https://deno.land/std@0.67.0/ws/mod.ts";
import { parse } from "https://deno.land/std@0.67.0/flags/mod.ts";
import chat from './chat.js';
async function fileExists(path) {
try {
const stats = await Deno.lstat(path);
return stats && stats.isFile;
} catch (e) {
if (e && e instanceof Deno.errors.NotFound) {
return false;
} else {
throw e;
}
}
}
const DEFAULT_PORT = 3000;
const argPort = parse(Deno.args).port;
const port = argPort ? parseInt(argPort) : DEFAULT_PORT
listenAndServe({ port: port }, async (req) => {
let url = req.url;
if (req.method === 'GET' && url === '/') {
url = '/index.html';
}
const position = req.url.indexOf('?');
if (position > -1) {
url = url.substring(0, position);
}
const path = `${Deno.cwd()}/public${url}`; // /index.html
if (await fileExists(path)) {
const content = await serveFile(req, path);
req.respond(content);
return;
}
if (req.method === "GET" && req.url === "/ws") {
if (acceptable(req)) {
acceptWebSocket({
conn: req.conn,
bufReader: req.r,
bufWriter: req.w,
headers: req.headers,
}).then(chat);
}
}
});
console.log(`Server started on port ${port}`);