forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_server.ts
executable file
·309 lines (286 loc) · 7.83 KB
/
file_server.ts
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#!/usr/bin/env -S deno --allow-net
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
// This program serves files in the current directory over HTTP.
// TODO Stream responses instead of reading them into memory.
// TODO Add tests like these:
// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js
const { ErrorKind, DenoError, cwd, args, stat, readDir, open } = Deno;
import { posix } from "../path/mod.ts";
import {
listenAndServe,
ServerRequest,
setContentLength,
Response
} from "./server.ts";
interface EntryInfo {
mode: string;
size: string;
url: string;
name: string;
}
const encoder = new TextEncoder();
const serverArgs = args.slice();
let CORSEnabled = false;
// TODO: switch to flags if we later want to add more options
for (let i = 0; i < serverArgs.length; i++) {
if (serverArgs[i] === "--cors") {
CORSEnabled = true;
serverArgs.splice(i, 1);
break;
}
}
const targetArg = serverArgs[1] || "";
const target = posix.isAbsolute(targetArg)
? posix.normalize(targetArg)
: posix.join(cwd(), targetArg);
const addr = `0.0.0.0:${serverArgs[2] || 4500}`;
function modeToString(isDir: boolean, maybeMode: number | null): string {
const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"];
if (maybeMode === null) {
return "(unknown mode)";
}
const mode = maybeMode!.toString(8);
if (mode.length < 3) {
return "(unknown mode)";
}
let output = "";
mode
.split("")
.reverse()
.slice(0, 3)
.forEach((v): void => {
output = modeMap[+v] + output;
});
output = `(${isDir ? "d" : "-"}${output})`;
return output;
}
function fileLenToString(len: number): string {
const multiplier = 1024;
let base = 1;
const suffix = ["B", "K", "M", "G", "T"];
let suffixIndex = 0;
while (base * multiplier < len) {
if (suffixIndex >= suffix.length - 1) {
break;
}
base *= multiplier;
suffixIndex++;
}
return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`;
}
async function serveFile(
req: ServerRequest,
filePath: string
): Promise<Response> {
const file = await open(filePath);
const fileInfo = await stat(filePath);
const headers = new Headers();
headers.set("content-length", fileInfo.len.toString());
headers.set("content-type", "text/plain");
const res = {
status: 200,
body: file,
headers
};
return res;
}
// TODO: simplify this after deno.stat and deno.readDir are fixed
async function serveDir(
req: ServerRequest,
dirPath: string
): Promise<Response> {
const dirUrl = `/${posix.relative(target, dirPath)}`;
const listEntry: EntryInfo[] = [];
const fileInfos = await readDir(dirPath);
for (const fileInfo of fileInfos) {
const filePath = posix.join(dirPath, fileInfo.name);
const fileUrl = posix.join(dirUrl, fileInfo.name);
if (fileInfo.name === "index.html" && fileInfo.isFile()) {
// in case index.html as dir...
return await serveFile(req, filePath);
}
// Yuck!
let mode = null;
try {
mode = (await stat(filePath)).mode;
} catch (e) {}
listEntry.push({
mode: modeToString(fileInfo.isDirectory(), mode),
size: fileInfo.isFile() ? fileLenToString(fileInfo.len) : "",
name: fileInfo.name,
url: fileUrl
});
}
listEntry.sort((a, b) =>
a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1
);
const formattedDirUrl = `${dirUrl.replace(/\/$/, "")}/`;
const page = encoder.encode(dirViewerTemplate(formattedDirUrl, listEntry));
const headers = new Headers();
headers.set("content-type", "text/html");
const res = {
status: 200,
body: page,
headers
};
setContentLength(res);
return res;
}
async function serveFallback(req: ServerRequest, e: Error): Promise<Response> {
if (e instanceof DenoError && e.kind === ErrorKind.NotFound) {
return {
status: 404,
body: encoder.encode("Not found")
};
} else {
return {
status: 500,
body: encoder.encode("Internal server error")
};
}
}
function serverLog(req: ServerRequest, res: Response): void {
const d = new Date().toISOString();
const dateFmt = `[${d.slice(0, 10)} ${d.slice(11, 19)}]`;
const s = `${dateFmt} "${req.method} ${req.url} ${req.proto}" ${res.status}`;
console.log(s);
}
function setCORS(res: Response): void {
if (!res.headers) {
res.headers = new Headers();
}
res.headers!.append("access-control-allow-origin", "*");
res.headers!.append(
"access-control-allow-headers",
"Origin, X-Requested-With, Content-Type, Accept, Range"
);
}
function dirViewerTemplate(dirname: string, entries: EntryInfo[]): string {
return html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Deno File Server</title>
<style>
:root {
--background-color: #fafafa;
--color: rgba(0, 0, 0, 0.87);
}
@media (prefers-color-scheme: dark) {
:root {
--background-color: #303030;
--color: #fff;
}
}
@media (min-width: 960px) {
main {
max-width: 960px;
}
body {
padding-left: 32px;
padding-right: 32px;
}
}
@media (min-width: 600px) {
main {
padding-left: 24px;
padding-right: 24px;
}
}
body {
background: var(--background-color);
color: var(--color);
font-family: "Roboto", "Helvetica", "Arial", sans-serif;
font-weight: 400;
line-height: 1.43;
font-size: 0.875rem;
}
a {
color: #2196f3;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
table th {
text-align: left;
}
table td {
padding: 12px 24px 0 0;
}
</style>
</head>
<body>
<main>
<h1>Index of ${dirname}</h1>
<table>
<tr>
<th>Mode</th>
<th>Size</th>
<th>Name</th>
</tr>
${entries.map(
entry => html`
<tr>
<td class="mode">
${entry.mode}
</td>
<td>
${entry.size}
</td>
<td>
<a href="${entry.url}">${entry.name}</a>
</td>
</tr>
`
)}
</table>
</main>
</body>
</html>
`;
}
function html(strings: TemplateStringsArray, ...values: unknown[]): string {
const l = strings.length - 1;
let html = "";
for (let i = 0; i < l; i++) {
let v = values[i];
if (v instanceof Array) {
v = v.join("");
}
const s = strings[i] + v;
html += s;
}
html += strings[l];
return html;
}
listenAndServe(
addr,
async (req): Promise<void> => {
const normalizedUrl = posix.normalize(req.url);
const decodedUrl = decodeURIComponent(normalizedUrl);
const fsPath = posix.join(target, decodedUrl);
let response: Response;
try {
const info = await stat(fsPath);
if (info.isDirectory()) {
response = await serveDir(req, fsPath);
} else {
response = await serveFile(req, fsPath);
}
} catch (e) {
console.error(e.message);
response = await serveFallback(req, e);
} finally {
if (CORSEnabled) {
setCORS(response);
}
serverLog(req, response);
req.respond(response);
}
}
);
console.log(`HTTP server listening on https://${addr}/`);