2019-07-28 07:10:29 -04:00
|
|
|
#!/usr/bin/env -S deno --allow-net
|
2019-02-07 11:45:47 -05:00
|
|
|
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
|
2018-12-09 15:35:26 -05:00
|
|
|
|
|
|
|
// 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
|
|
|
|
|
2019-12-13 21:01:32 -05:00
|
|
|
const { ErrorKind, DenoError, args, stat, readDir, open, exit } = Deno;
|
2019-12-02 19:14:25 -05:00
|
|
|
import { posix } from "../path/mod.ts";
|
2018-12-17 11:49:10 -05:00
|
|
|
import {
|
|
|
|
listenAndServe,
|
|
|
|
ServerRequest,
|
|
|
|
setContentLength,
|
2019-02-19 12:38:19 -05:00
|
|
|
Response
|
2019-02-02 18:57:38 -05:00
|
|
|
} from "./server.ts";
|
2019-12-13 21:01:32 -05:00
|
|
|
import { parse } from "../flags/mod.ts";
|
2018-12-11 17:56:32 -05:00
|
|
|
|
2019-12-02 19:14:25 -05:00
|
|
|
interface EntryInfo {
|
|
|
|
mode: string;
|
|
|
|
size: string;
|
|
|
|
url: string;
|
|
|
|
name: string;
|
|
|
|
}
|
2018-11-07 13:16:07 -05:00
|
|
|
|
2019-12-13 21:01:32 -05:00
|
|
|
interface FileServerArgs {
|
|
|
|
_: string[];
|
|
|
|
// -p --port
|
|
|
|
p: number;
|
|
|
|
port: number;
|
|
|
|
// --cors
|
|
|
|
cors: boolean;
|
|
|
|
// -h --help
|
|
|
|
h: boolean;
|
|
|
|
help: boolean;
|
|
|
|
}
|
|
|
|
|
2019-12-02 19:14:25 -05:00
|
|
|
const encoder = new TextEncoder();
|
2019-12-13 21:01:32 -05:00
|
|
|
|
|
|
|
const serverArgs = parse(args) as FileServerArgs;
|
|
|
|
|
|
|
|
const CORSEnabled = serverArgs.cors ? true : false;
|
|
|
|
const target = posix.resolve(serverArgs._[1] || "");
|
|
|
|
const addr = `0.0.0.0:${serverArgs.port || serverArgs.p || 4500}`;
|
|
|
|
|
|
|
|
if (serverArgs.h || serverArgs.help) {
|
|
|
|
console.log(`Deno File Server
|
|
|
|
Serves a local directory in HTTP.
|
|
|
|
|
|
|
|
INSTALL:
|
|
|
|
deno install file_server https://deno.land/std/http/file_server.ts --allow-net --allow-read
|
|
|
|
|
|
|
|
USAGE:
|
|
|
|
file_server [path] [options]
|
|
|
|
|
|
|
|
OPTIONS:
|
|
|
|
-h, --help Prints help information
|
|
|
|
-p, --port <PORT> Set port
|
|
|
|
--cors Enable CORS via the "Access-Control-Allow-Origin" header`);
|
|
|
|
exit();
|
2018-12-23 22:50:49 -05:00
|
|
|
}
|
2018-12-09 15:35:26 -05:00
|
|
|
|
2019-03-08 13:04:02 -05:00
|
|
|
function modeToString(isDir: boolean, maybeMode: number | null): string {
|
2018-12-11 17:56:32 -05:00
|
|
|
const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"];
|
2018-11-07 13:16:07 -05:00
|
|
|
|
2018-12-11 17:56:32 -05:00
|
|
|
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)
|
2019-11-13 13:42:34 -05:00
|
|
|
.forEach((v): void => {
|
|
|
|
output = modeMap[+v] + output;
|
|
|
|
});
|
2018-12-11 17:56:32 -05:00
|
|
|
output = `(${isDir ? "d" : "-"}${output})`;
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2019-03-08 13:04:02 -05:00
|
|
|
function fileLenToString(len: number): string {
|
2019-05-31 08:39:05 -04:00
|
|
|
const multiplier = 1024;
|
2018-12-11 17:56:32 -05:00
|
|
|
let base = 1;
|
|
|
|
const suffix = ["B", "K", "M", "G", "T"];
|
|
|
|
let suffixIndex = 0;
|
|
|
|
|
2019-05-31 08:39:05 -04:00
|
|
|
while (base * multiplier < len) {
|
2018-12-11 17:56:32 -05:00
|
|
|
if (suffixIndex >= suffix.length - 1) {
|
|
|
|
break;
|
2018-12-09 15:35:26 -05:00
|
|
|
}
|
2019-05-31 08:39:05 -04:00
|
|
|
base *= multiplier;
|
2018-12-11 17:56:32 -05:00
|
|
|
suffixIndex++;
|
2018-12-09 15:35:26 -05:00
|
|
|
}
|
2018-12-11 17:56:32 -05:00
|
|
|
|
|
|
|
return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`;
|
|
|
|
}
|
|
|
|
|
2019-03-08 13:04:02 -05:00
|
|
|
async function serveFile(
|
|
|
|
req: ServerRequest,
|
2019-08-15 11:59:43 -04:00
|
|
|
filePath: string
|
2019-03-08 13:04:02 -05:00
|
|
|
): Promise<Response> {
|
2019-12-12 02:59:46 -05:00
|
|
|
const [file, fileInfo] = await Promise.all([open(filePath), stat(filePath)]);
|
2019-03-08 13:04:02 -05:00
|
|
|
const headers = new Headers();
|
|
|
|
headers.set("content-length", fileInfo.len.toString());
|
2019-12-14 03:03:30 -05:00
|
|
|
headers.set("content-type", "text/plain; charset=utf-8");
|
2019-03-08 13:04:02 -05:00
|
|
|
|
|
|
|
const res = {
|
|
|
|
status: 200,
|
|
|
|
body: file,
|
|
|
|
headers
|
|
|
|
};
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2018-12-11 17:56:32 -05:00
|
|
|
// TODO: simplify this after deno.stat and deno.readDir are fixed
|
2019-03-08 13:04:02 -05:00
|
|
|
async function serveDir(
|
|
|
|
req: ServerRequest,
|
2019-08-15 11:59:43 -04:00
|
|
|
dirPath: string
|
2019-03-08 13:04:02 -05:00
|
|
|
): Promise<Response> {
|
2019-08-15 11:59:43 -04:00
|
|
|
const dirUrl = `/${posix.relative(target, dirPath)}`;
|
2019-12-02 19:14:25 -05:00
|
|
|
const listEntry: EntryInfo[] = [];
|
2018-12-11 17:56:32 -05:00
|
|
|
const fileInfos = await readDir(dirPath);
|
2019-08-15 11:59:43 -04:00
|
|
|
for (const fileInfo of fileInfos) {
|
|
|
|
const filePath = posix.join(dirPath, fileInfo.name);
|
2019-10-05 12:02:34 -04:00
|
|
|
const fileUrl = posix.join(dirUrl, fileInfo.name);
|
2019-08-15 11:59:43 -04:00
|
|
|
if (fileInfo.name === "index.html" && fileInfo.isFile()) {
|
2018-12-11 17:56:32 -05:00
|
|
|
// in case index.html as dir...
|
2019-08-15 11:59:43 -04:00
|
|
|
return await serveFile(req, filePath);
|
2018-12-11 17:56:32 -05:00
|
|
|
}
|
|
|
|
// Yuck!
|
|
|
|
let mode = null;
|
|
|
|
try {
|
2019-08-15 11:59:43 -04:00
|
|
|
mode = (await stat(filePath)).mode;
|
2018-12-11 17:56:32 -05:00
|
|
|
} catch (e) {}
|
2019-06-22 10:52:56 -04:00
|
|
|
listEntry.push({
|
2019-12-02 19:14:25 -05:00
|
|
|
mode: modeToString(fileInfo.isDirectory(), mode),
|
|
|
|
size: fileInfo.isFile() ? fileLenToString(fileInfo.len) : "",
|
2019-08-15 11:59:43 -04:00
|
|
|
name: fileInfo.name,
|
2019-12-02 19:14:25 -05:00
|
|
|
url: fileUrl
|
2019-06-22 10:52:56 -04:00
|
|
|
});
|
2018-12-11 17:56:32 -05:00
|
|
|
}
|
2019-12-02 19:14:25 -05:00
|
|
|
listEntry.sort((a, b) =>
|
|
|
|
a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1
|
2018-12-11 17:56:32 -05:00
|
|
|
);
|
2019-12-02 19:14:25 -05:00
|
|
|
const formattedDirUrl = `${dirUrl.replace(/\/$/, "")}/`;
|
|
|
|
const page = encoder.encode(dirViewerTemplate(formattedDirUrl, listEntry));
|
2018-12-11 17:56:32 -05:00
|
|
|
|
2018-12-09 15:35:26 -05:00
|
|
|
const headers = new Headers();
|
2018-12-11 17:56:32 -05:00
|
|
|
headers.set("content-type", "text/html");
|
|
|
|
|
|
|
|
const res = {
|
|
|
|
status: 200,
|
|
|
|
body: page,
|
|
|
|
headers
|
|
|
|
};
|
|
|
|
setContentLength(res);
|
2018-12-12 04:38:46 -05:00
|
|
|
return res;
|
2018-12-11 17:56:32 -05:00
|
|
|
}
|
|
|
|
|
2019-03-08 13:04:02 -05:00
|
|
|
async function serveFallback(req: ServerRequest, e: Error): Promise<Response> {
|
2019-12-12 00:05:26 -05:00
|
|
|
if (e instanceof DenoError && e.kind === ErrorKind.NotFound) {
|
2018-12-17 11:49:10 -05:00
|
|
|
return {
|
|
|
|
status: 404,
|
|
|
|
body: encoder.encode("Not found")
|
2018-12-12 04:38:46 -05:00
|
|
|
};
|
2018-12-11 17:56:32 -05:00
|
|
|
} else {
|
2018-12-12 04:38:46 -05:00
|
|
|
return {
|
2018-12-11 17:56:32 -05:00
|
|
|
status: 500,
|
|
|
|
body: encoder.encode("Internal server error")
|
2018-12-12 04:38:46 -05:00
|
|
|
};
|
2018-12-11 17:56:32 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-08 13:04:02 -05:00
|
|
|
function serverLog(req: ServerRequest, res: Response): void {
|
2018-12-12 04:38:46 -05:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2019-03-08 13:04:02 -05:00
|
|
|
function setCORS(res: Response): void {
|
2018-12-23 22:50:49 -05:00
|
|
|
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"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-12-02 19:14:25 -05:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2019-04-24 07:41:23 -04:00
|
|
|
listenAndServe(
|
|
|
|
addr,
|
|
|
|
async (req): Promise<void> => {
|
2019-08-15 11:59:43 -04:00
|
|
|
const normalizedUrl = posix.normalize(req.url);
|
2019-12-10 07:11:55 -05:00
|
|
|
const decodedUrl = decodeURIComponent(normalizedUrl);
|
|
|
|
const fsPath = posix.join(target, decodedUrl);
|
2018-12-11 17:56:32 -05:00
|
|
|
|
2019-04-24 07:41:23 -04:00
|
|
|
let response: Response;
|
|
|
|
try {
|
2019-08-15 11:59:43 -04:00
|
|
|
const info = await stat(fsPath);
|
|
|
|
if (info.isDirectory()) {
|
|
|
|
response = await serveDir(req, fsPath);
|
2019-04-24 07:41:23 -04:00
|
|
|
} else {
|
2019-08-15 11:59:43 -04:00
|
|
|
response = await serveFile(req, fsPath);
|
2019-04-24 07:41:23 -04:00
|
|
|
}
|
|
|
|
} catch (e) {
|
2019-12-12 00:05:26 -05:00
|
|
|
console.error(e.message);
|
2019-04-24 07:41:23 -04:00
|
|
|
response = await serveFallback(req, e);
|
|
|
|
} finally {
|
|
|
|
if (CORSEnabled) {
|
|
|
|
setCORS(response);
|
|
|
|
}
|
|
|
|
serverLog(req, response);
|
|
|
|
req.respond(response);
|
2018-12-23 22:50:49 -05:00
|
|
|
}
|
2018-12-11 17:56:32 -05:00
|
|
|
}
|
2019-04-24 07:41:23 -04:00
|
|
|
);
|
2018-11-07 13:16:07 -05:00
|
|
|
|
|
|
|
console.log(`HTTP server listening on http://${addr}/`);
|