-
Notifications
You must be signed in to change notification settings - Fork 1
/
file-server.js
245 lines (206 loc) · 7.94 KB
/
file-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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { config } from "./_config.js";
const handlers = {};
function withoutTrailingSlash(url) {
return url.replace(/\/$/, "");
}
// https://docs.deno.com/runtime/tutorials/file_server
async function getStaticFile ({ filepath, request }) {
console.log({ filepath });
// Try opening the file
let file;
try {
// If it's a file (has a file extension), open it
if (new RegExp(/\.[a-zA-Z]+$/).test(filepath)) {
file = await Deno.open(filepath, { read: true });
} else {
// If it's a directory, look for an index.html file
file = await Deno.open(withoutTrailingSlash(filepath) + "/index.html", { read: true });
// Add trailing slashes to URLs: /wildflowers => /wildflowers/
const url = new URL(request.url);
if (!url.pathname.endsWith("/")) {
return Response.redirect(url.origin + url.pathname + "/" + url.search + url.hash, 302);
}
}
} catch {
// If the file cannot be opened, return a "404 Not Found" response
return handlers["/404/"]({ request });
}
// Build a readable stream so the file doesn't have to be fully loaded into
// memory while we send it
const readableStream = file.readable;
const headers = {};
if (filepath.endsWith(".html")) {
headers["content-type"] = "text/html; charset=utf-8";
} else if (filepath.endsWith(".txt")) {
headers["content-type"] = "text/plain; charset=utf-8";
} else if (filepath.endsWith(".xml")) {
headers["content-type"] = "text/xml; charset=utf-8";
} else if (filepath.endsWith(".css")) {
headers["content-type"] = "text/css; charset=utf-8";
} else if (filepath.endsWith(".js") || filepath.endsWith(".mjs")) {
headers["content-type"] = "application/javascript; charset=utf-8";
} else if (filepath.endsWith(".json")) {
headers["content-type"] = "application/json; charset=utf-8";
} else if (filepath.endsWith(".jpg") || filepath.endsWith(".jpeg")) {
headers["content-type"] = "image/jpeg";
} else if (filepath.endsWith(".webp")) {
headers["content-type"] = "image/webp";
} else if (filepath.endsWith(".avif")) {
headers["content-type"] = "image/avif";
} else if (filepath.endsWith(".png")) {
headers["content-type"] = "image/png";
} else if (filepath.endsWith(".svg")) {
headers["content-type"] = "image/svg+xml";
}
// Build and send the response
return new Response(readableStream, {
headers: headers,
});
}
function getStaticFileHandler ({ folder, pathPrefix }) {
return ({ request }) => {
// Use the request pathname as filepath
const url = new URL(request.url);
const filepath = folder + decodeURIComponent(url.pathname).replace(pathPrefix, "");
return getStaticFile({ filepath, request });
}
}
function serveStaticFiles({ folder }) {
console.log(`📂 Preparing static files`);
handlers["/*"] = getStaticFileHandler({ folder, pathPrefix: "" });
}
function serveError404Page({ folder }) {
console.log(`🚥 Preparing 404 "not found" page`);
console.log("");
handlers["/404/"] = async function ({ request }) {
// Try returning a 404.html file, if one exists
try {
const filepath = `${folder}/404.html`;
const file = await Deno.open(filepath, { read: true });
// Build a readable stream so the file doesn't have to be fully loaded into
// memory while we send it
const readableStream = file.readable;
return new Response(readableStream, {
status: 404,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
} catch {
// If a 404.html file does’t exist, return a simple message
return new Response("<html><title>Not found</title><body>Not found</body></html>", {
status: 404,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
}
};
}
async function getRedirects({ folder, redirectsFilePath }) {
const redirects = [];
// Try opening a redirects file, if one exists
try {
// https://docs.deno.com/deploy/api/runtime-fs#denoreadtextfile
const redirectsText = await Deno.readTextFile(`${folder}${redirectsFilePath}`);
const redirectsLines = redirectsText.split("\n");
for (const line of redirectsLines) {
const [from, to] = line.split(/\s+/);
if (from && to) {
// handlers[from] = () => Response.redirect(to, 302);
redirects.push({ from, to });
}
}
} catch {
console.log(`Something went wrong while getting redirects from: ${folder}${redirectsFilePath}`);
}
return redirects;
}
function removeTrailingSlash(url) {
if (url === "/") return url;
return url.replace(/\/$/, "");
}
async function serve({ folder, redirectsFilePath, port, hostname }) {
console.log("");
console.log("- - - - - - - - - - - - - - - - - - - - - - -");
console.log("⏱️ ", "Starting server");
console.log("- - - - - - - - - - - - - - - - - - - - - - -");
console.log("");
serveStaticFiles({ folder });
serveError404Page({ folder });
const server = Deno.serve({ port, hostname }, async (request) => {
const url = new URL(request.url);
console.log({ url, pathname: url.pathname });
const redirects = await getRedirects({ folder, redirectsFilePath });
for (const redirect of redirects) {
try {
// A) Simple redirect
if (removeTrailingSlash(url.pathname) === removeTrailingSlash(redirect.from)) {
const redirectTo =
redirect.to.startsWith("http")
? redirect.to
: url.origin + redirect.to;
return Response.redirect(redirectTo, 302);
}
// B) Wildcard redirect (splat)
if (
redirect.from.startsWith("http") &&
redirect.from.endsWith("/*") &&
redirect.to.startsWith("http") &&
redirect.to.endsWith("/:splat")
) {
// request.url: https://www.example.com/ahoy/there/
// redirect.from: https://www.example.com/*
// redirect.to: https://example.com/:splat
const fromURL = new URL(redirect.from);
// { hostname: "www.example.com", ... }
const to = redirect.to.replace(/\/:splat$/, "");
// https://example.com
if (url.hostname === fromURL.hostname) {
return Response.redirect(to + url.pathname + url.search + url.hash, 302);
// "https://example.com/ahoy/there"
}
};
} catch(e) {
console.error(e);
}
}
// Add trailing slashes to URLs: /wildflowers => /wildflowers/
if (handlers[url.pathname + "/"]) {
return Response.redirect(url.origin + url.pathname + "/" + url.search + url.hash, 302);
} else if (handlers[url.pathname]) {
return handlers[url.pathname]({ request });
} else {
for (let key in handlers) {
if (key.endsWith("*") === false) continue;
const path = key.replace(/\*$/, "");
if (url.pathname.startsWith(path)) {
return handlers[key]({ request });
}
}
return handlers["/404/"]({ request });
}
});
// If we’re not in development mode (using --watch)
if (!Deno.args.includes("--dev")) {
// Shutdown the server gracefully when the process is interrupted.
Deno.addSignalListener("SIGINT", () => {
console.log("");
console.log(chalk.cyan("- - - - - - - - - - - - - - - - - - - - - - -"));
console.log("💁", chalk.cyan(`Received "SIGINT". Server shutting down...`));
console.log(chalk.cyan("- - - - - - - - - - - - - - - - - - - - - - -"));
console.log("");
server.shutdown();
});
}
console.log("");
console.log("- - - - - - - - - - - - - - - - - - - - - - -");
console.log("💁", `Server ready on`, `http://${hostname}:${port}`);
console.log("- - - - - - - - - - - - - - - - - - - - - - -");
console.log("");
}
const port = !isNaN(Number(config.serverPort)) ? Number(config.serverPort) : 4000;
const hostname = config.serverHostname;
const folder = ".";
const redirectsFilePath = `/_redirects`;
serve({ folder, redirectsFilePath, port, hostname });