2020-05-27 19:24:57 +00:00
|
|
|
#!/usr/bin/env -S deno run --allow-net --allow-read
|
2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2018-12-09 20:35:26 +00:00
|
|
|
|
|
|
|
// This program serves files in the current directory over HTTP.
|
2021-01-16 23:32:59 +00:00
|
|
|
// TODO(bartlomieju): Add tests like these:
|
2018-12-09 20:35:26 +00:00
|
|
|
// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js
|
|
|
|
|
2023-05-10 05:27:25 +00:00
|
|
|
/**
|
2024-06-25 09:32:34 +00:00
|
|
|
* Contains functions {@linkcode serveDir} and {@linkcode serveFile} for
|
|
|
|
* building a static file server.
|
2023-05-10 05:27:25 +00:00
|
|
|
*
|
2024-06-25 09:32:34 +00:00
|
|
|
* This module can also be used as a CLI. If you want to run it directly:
|
2023-05-10 05:27:25 +00:00
|
|
|
*
|
|
|
|
* ```shell
|
|
|
|
* > # start server
|
2024-06-25 09:32:34 +00:00
|
|
|
* > deno run --allow-net --allow-read --allow-sys jsr:@std/http/file-server
|
2023-05-10 05:27:25 +00:00
|
|
|
* > # show help
|
2024-06-25 09:32:34 +00:00
|
|
|
* > deno run jsr:@std/http/file-server --help
|
2023-05-10 05:27:25 +00:00
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* If you want to install and run:
|
|
|
|
*
|
|
|
|
* ```shell
|
|
|
|
* > # install
|
2024-06-25 09:32:34 +00:00
|
|
|
* > deno install --allow-net --allow-read --allow-sys --global jsr:@std/http/file-server
|
2023-05-10 05:27:25 +00:00
|
|
|
* > # start server
|
2024-06-25 09:32:34 +00:00
|
|
|
* > file-server
|
2023-05-10 05:27:25 +00:00
|
|
|
* > # show help
|
2024-06-25 09:32:34 +00:00
|
|
|
* > file-server --help
|
2023-05-10 05:27:25 +00:00
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @module
|
|
|
|
*/
|
|
|
|
|
2024-04-29 02:57:30 +00:00
|
|
|
import { join as posixJoin } from "@std/path/posix/join";
|
|
|
|
import { normalize as posixNormalize } from "@std/path/posix/normalize";
|
|
|
|
import { extname } from "@std/path/extname";
|
|
|
|
import { join } from "@std/path/join";
|
|
|
|
import { relative } from "@std/path/relative";
|
|
|
|
import { resolve } from "@std/path/resolve";
|
|
|
|
import { SEPARATOR_PATTERN } from "@std/path/constants";
|
|
|
|
import { contentType } from "@std/media-types/content-type";
|
2024-07-10 06:27:34 +00:00
|
|
|
import { eTag, ifNoneMatch } from "./etag.ts";
|
2023-11-17 02:26:11 +00:00
|
|
|
import {
|
|
|
|
isRedirectStatus,
|
|
|
|
STATUS_CODE,
|
|
|
|
STATUS_TEXT,
|
|
|
|
type StatusCode,
|
|
|
|
} from "./status.ts";
|
2024-04-29 02:57:30 +00:00
|
|
|
import { ByteSliceStream } from "@std/streams/byte-slice-stream";
|
|
|
|
import { parseArgs } from "@std/cli/parse-args";
|
|
|
|
import denoConfig from "./deno.json" with { type: "json" };
|
|
|
|
import { format as formatBytes } from "@std/fmt/bytes";
|
2024-05-30 02:17:40 +00:00
|
|
|
import { getNetworkAddress } from "@std/net/get-network-address";
|
2024-08-06 13:40:47 +00:00
|
|
|
import { HEADER } from "./header.ts";
|
2024-08-10 18:42:34 +00:00
|
|
|
import { METHOD } from "./method.ts";
|
2023-05-07 06:48:39 +00:00
|
|
|
|
2019-12-03 00:14:25 +00:00
|
|
|
interface EntryInfo {
|
|
|
|
mode: string;
|
|
|
|
size: string;
|
|
|
|
url: string;
|
|
|
|
name: string;
|
|
|
|
}
|
2018-11-07 18:16:07 +00:00
|
|
|
|
2023-04-18 08:07:28 +00:00
|
|
|
const ENV_PERM_STATUS =
|
|
|
|
Deno.permissions.querySync?.({ name: "env", variable: "DENO_DEPLOYMENT_ID" })
|
|
|
|
.state ?? "granted"; // for deno deploy
|
|
|
|
const DENO_DEPLOYMENT_ID = ENV_PERM_STATUS === "granted"
|
|
|
|
? Deno.env.get("DENO_DEPLOYMENT_ID")
|
|
|
|
: undefined;
|
|
|
|
const HASHED_DENO_DEPLOYMENT_ID = DENO_DEPLOYMENT_ID
|
2024-07-10 06:27:34 +00:00
|
|
|
? eTag(DENO_DEPLOYMENT_ID, { weak: true })
|
2023-04-18 08:07:28 +00:00
|
|
|
: undefined;
|
|
|
|
|
2019-03-08 18:04:02 +00:00
|
|
|
function modeToString(isDir: boolean, maybeMode: number | null): string {
|
2018-12-11 22:56:32 +00:00
|
|
|
const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"];
|
2018-11-07 18:16:07 +00:00
|
|
|
|
2018-12-11 22:56:32 +00:00
|
|
|
if (maybeMode === null) {
|
|
|
|
return "(unknown mode)";
|
|
|
|
}
|
2024-06-25 06:16:28 +00:00
|
|
|
const mode = maybeMode.toString(8).padStart(3, "0");
|
2018-12-11 22:56:32 +00:00
|
|
|
let output = "";
|
|
|
|
mode
|
|
|
|
.split("")
|
|
|
|
.reverse()
|
|
|
|
.slice(0, 3)
|
2022-08-24 01:21:57 +00:00
|
|
|
.forEach((v) => {
|
2022-01-09 01:51:55 +00:00
|
|
|
output = `${modeMap[+v]} ${output}`;
|
2019-11-13 18:42:34 +00:00
|
|
|
});
|
2022-01-09 01:51:55 +00:00
|
|
|
output = `${isDir ? "d" : "-"} ${output}`;
|
2018-12-11 22:56:32 +00:00
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2023-11-17 02:26:11 +00:00
|
|
|
function createStandardResponse(status: StatusCode, init?: ResponseInit) {
|
|
|
|
const statusText = STATUS_TEXT[status];
|
|
|
|
return new Response(statusText, { status, statusText, ...init });
|
2023-10-13 07:24:58 +00:00
|
|
|
}
|
|
|
|
|
2023-05-04 04:58:13 +00:00
|
|
|
/**
|
|
|
|
* parse range header.
|
|
|
|
*
|
|
|
|
* ```ts ignore
|
|
|
|
* parseRangeHeader("bytes=0-100", 500); // => { start: 0, end: 100 }
|
|
|
|
* parseRangeHeader("bytes=0-", 500); // => { start: 0, end: 499 }
|
|
|
|
* parseRangeHeader("bytes=-100", 500); // => { start: 400, end: 499 }
|
|
|
|
* parseRangeHeader("bytes=invalid", 500); // => null
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* Note: Currently, no support for multiple Ranges (e.g. `bytes=0-10, 20-30`)
|
|
|
|
*/
|
|
|
|
function parseRangeHeader(rangeValue: string, fileSize: number) {
|
|
|
|
const rangeRegex = /bytes=(?<start>\d+)?-(?<end>\d+)?$/u;
|
|
|
|
const parsed = rangeValue.match(rangeRegex);
|
|
|
|
|
|
|
|
if (!parsed || !parsed.groups) {
|
|
|
|
// failed to parse range header
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const { start, end } = parsed.groups;
|
|
|
|
if (start !== undefined) {
|
|
|
|
if (end !== undefined) {
|
|
|
|
return { start: +start, end: +end };
|
|
|
|
} else {
|
|
|
|
return { start: +start, end: fileSize - 1 };
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (end !== undefined) {
|
|
|
|
// example: `bytes=-100` means the last 100 bytes.
|
|
|
|
return { start: fileSize - +end, end: fileSize - 1 };
|
|
|
|
} else {
|
|
|
|
// failed to parse range header
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-25 09:32:34 +00:00
|
|
|
/** Options for {@linkcode serveFile}. */
|
2022-06-01 14:56:57 +00:00
|
|
|
export interface ServeFileOptions {
|
2024-06-25 09:32:34 +00:00
|
|
|
/**
|
|
|
|
* The algorithm to use for generating the ETag.
|
2022-11-25 11:40:23 +00:00
|
|
|
*
|
2023-04-13 09:43:43 +00:00
|
|
|
* @default {"SHA-256"}
|
2022-11-25 11:40:23 +00:00
|
|
|
*/
|
2023-04-13 09:43:43 +00:00
|
|
|
etagAlgorithm?: AlgorithmIdentifier;
|
2024-07-11 09:21:37 +00:00
|
|
|
/**
|
|
|
|
* An optional object returned by {@linkcode Deno.stat}. It is used for
|
|
|
|
* optimization purposes.
|
|
|
|
*
|
|
|
|
* Defaults to the result of calling {@linkcode Deno.stat} with the provided
|
|
|
|
* `filePath`.
|
|
|
|
*/
|
2022-04-18 02:41:11 +00:00
|
|
|
fileInfo?: Deno.FileInfo;
|
|
|
|
}
|
|
|
|
|
2020-11-20 02:59:45 +00:00
|
|
|
/**
|
2024-06-25 09:32:34 +00:00
|
|
|
* Resolves a {@linkcode Response} with the requested file as the body.
|
2024-05-22 19:09:08 +00:00
|
|
|
*
|
|
|
|
* @example Usage
|
|
|
|
* ```ts no-eval
|
|
|
|
* import { serveFile } from "@std/http/file-server";
|
|
|
|
*
|
|
|
|
* Deno.serve((req) => {
|
|
|
|
* return serveFile(req, "README.md");
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
2021-09-06 08:06:59 +00:00
|
|
|
* @param req The server request context used to cleanup the file handle.
|
|
|
|
* @param filePath Path of the file to serve.
|
2024-07-19 04:12:23 +00:00
|
|
|
* @param options Additional options.
|
2024-05-22 19:09:08 +00:00
|
|
|
* @returns A response for the request.
|
2020-11-20 02:59:45 +00:00
|
|
|
*/
|
2020-04-01 16:51:01 +00:00
|
|
|
export async function serveFile(
|
2021-08-31 14:36:30 +00:00
|
|
|
req: Request,
|
2020-07-14 19:24:17 +00:00
|
|
|
filePath: string,
|
2024-07-19 04:12:23 +00:00
|
|
|
options?: ServeFileOptions,
|
2019-03-08 18:04:02 +00:00
|
|
|
): Promise<Response> {
|
2024-08-10 18:42:34 +00:00
|
|
|
if (req.method !== METHOD.Get) {
|
2024-08-07 12:35:30 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.MethodNotAllowed);
|
|
|
|
}
|
|
|
|
|
2024-07-19 04:12:23 +00:00
|
|
|
let { etagAlgorithm: algorithm, fileInfo } = options ?? {};
|
|
|
|
|
2022-08-16 05:49:38 +00:00
|
|
|
try {
|
2022-09-15 14:34:22 +00:00
|
|
|
fileInfo ??= await Deno.stat(filePath);
|
2022-08-16 05:49:38 +00:00
|
|
|
} catch (error) {
|
|
|
|
if (error instanceof Deno.errors.NotFound) {
|
|
|
|
await req.body?.cancel();
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.NotFound);
|
2022-08-16 05:49:38 +00:00
|
|
|
} else {
|
|
|
|
throw error;
|
|
|
|
}
|
2022-04-18 02:41:11 +00:00
|
|
|
}
|
2022-08-16 05:49:38 +00:00
|
|
|
|
2022-09-15 14:34:22 +00:00
|
|
|
if (fileInfo.isDirectory) {
|
|
|
|
await req.body?.cancel();
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.NotFound);
|
2022-09-15 14:34:22 +00:00
|
|
|
}
|
|
|
|
|
2023-05-06 08:58:27 +00:00
|
|
|
const headers = createBaseHeaders();
|
2021-07-22 06:12:40 +00:00
|
|
|
|
|
|
|
// Set date header if access timestamp is available
|
2023-04-19 06:42:33 +00:00
|
|
|
if (fileInfo.atime) {
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.Date, fileInfo.atime.toUTCString());
|
2021-07-22 06:12:40 +00:00
|
|
|
}
|
|
|
|
|
2023-04-18 08:07:28 +00:00
|
|
|
const etag = fileInfo.mtime
|
2024-07-10 06:27:34 +00:00
|
|
|
? await eTag(fileInfo, { algorithm })
|
2023-04-18 08:07:28 +00:00
|
|
|
: await HASHED_DENO_DEPLOYMENT_ID;
|
2023-02-14 07:47:38 +00:00
|
|
|
|
|
|
|
// Set last modified header if last modification timestamp is available
|
|
|
|
if (fileInfo.mtime) {
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.LastModified, fileInfo.mtime.toUTCString());
|
2023-02-14 07:47:38 +00:00
|
|
|
}
|
|
|
|
if (etag) {
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ETag, etag);
|
2023-02-14 07:47:38 +00:00
|
|
|
}
|
2021-07-22 06:12:40 +00:00
|
|
|
|
2023-02-14 07:47:38 +00:00
|
|
|
if (etag || fileInfo.mtime) {
|
2021-08-03 06:58:31 +00:00
|
|
|
// If a `if-none-match` header is present and the value matches the tag or
|
|
|
|
// if a `if-modified-since` header is present and the value is bigger than
|
|
|
|
// the access timestamp value, then return 304
|
2024-08-06 13:40:47 +00:00
|
|
|
const ifNoneMatchValue = req.headers.get(HEADER.IfNoneMatch);
|
|
|
|
const ifModifiedSinceValue = req.headers.get(HEADER.IfModifiedSince);
|
2021-08-03 06:58:31 +00:00
|
|
|
if (
|
2023-04-12 11:51:19 +00:00
|
|
|
(!ifNoneMatch(ifNoneMatchValue, etag)) ||
|
|
|
|
(ifNoneMatchValue === null &&
|
2023-02-14 07:47:38 +00:00
|
|
|
fileInfo.mtime &&
|
2023-04-12 11:51:19 +00:00
|
|
|
ifModifiedSinceValue &&
|
|
|
|
fileInfo.mtime.getTime() <
|
|
|
|
new Date(ifModifiedSinceValue).getTime() + 1000)
|
2021-08-03 06:58:31 +00:00
|
|
|
) {
|
2023-11-17 02:26:11 +00:00
|
|
|
const status = STATUS_CODE.NotModified;
|
|
|
|
return new Response(null, {
|
|
|
|
status,
|
|
|
|
statusText: STATUS_TEXT[status],
|
|
|
|
headers,
|
|
|
|
});
|
2021-07-22 06:12:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-19 06:42:33 +00:00
|
|
|
// Set mime-type using the file extension in filePath
|
|
|
|
const contentTypeValue = contentType(extname(filePath));
|
|
|
|
if (contentTypeValue) {
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ContentType, contentTypeValue);
|
2023-04-19 06:42:33 +00:00
|
|
|
}
|
|
|
|
|
2023-05-04 04:58:13 +00:00
|
|
|
const fileSize = fileInfo.size;
|
2021-07-22 06:12:40 +00:00
|
|
|
|
2024-08-06 13:40:47 +00:00
|
|
|
const rangeValue = req.headers.get(HEADER.Range);
|
2021-07-22 06:12:40 +00:00
|
|
|
|
2023-05-04 04:58:13 +00:00
|
|
|
// handle range request
|
|
|
|
// Note: Some clients add a Range header to all requests to limit the size of the response.
|
|
|
|
// If the file is empty, ignore the range header and respond with a 200 rather than a 416.
|
|
|
|
// https://github.com/golang/go/blob/0d347544cbca0f42b160424f6bc2458ebcc7b3fc/src/net/http/fs.go#L273-L276
|
|
|
|
if (rangeValue && 0 < fileSize) {
|
|
|
|
const parsed = parseRangeHeader(rangeValue, fileSize);
|
2021-07-22 06:12:40 +00:00
|
|
|
|
2023-05-04 04:58:13 +00:00
|
|
|
// Returns 200 OK if parsing the range header fails
|
|
|
|
if (!parsed) {
|
|
|
|
// Set content length
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ContentLength, `${fileSize}`);
|
2021-07-22 06:12:40 +00:00
|
|
|
|
2023-05-04 04:58:13 +00:00
|
|
|
const file = await Deno.open(filePath);
|
2023-11-17 02:26:11 +00:00
|
|
|
const status = STATUS_CODE.OK;
|
|
|
|
return new Response(file.readable, {
|
|
|
|
status,
|
|
|
|
statusText: STATUS_TEXT[status],
|
|
|
|
headers,
|
|
|
|
});
|
2023-05-04 04:58:13 +00:00
|
|
|
}
|
2023-04-19 06:42:33 +00:00
|
|
|
|
2023-05-04 04:58:13 +00:00
|
|
|
// Return 416 Range Not Satisfiable if invalid range header value
|
|
|
|
if (
|
|
|
|
parsed.end < 0 ||
|
|
|
|
parsed.end < parsed.start ||
|
|
|
|
fileSize <= parsed.start
|
|
|
|
) {
|
|
|
|
// Set the "Content-range" header
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ContentRange, `bytes */${fileSize}`);
|
2023-05-04 04:58:13 +00:00
|
|
|
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(
|
|
|
|
STATUS_CODE.RangeNotSatisfiable,
|
2023-05-04 04:58:13 +00:00
|
|
|
{ headers },
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// clamps the range header value
|
|
|
|
const start = Math.max(0, parsed.start);
|
|
|
|
const end = Math.min(parsed.end, fileSize - 1);
|
|
|
|
|
|
|
|
// Set the "Content-range" header
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ContentRange, `bytes ${start}-${end}/${fileSize}`);
|
2023-05-04 04:58:13 +00:00
|
|
|
|
|
|
|
// Set content length
|
|
|
|
const contentLength = end - start + 1;
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ContentLength, `${contentLength}`);
|
2023-05-04 04:58:13 +00:00
|
|
|
|
|
|
|
// Return 206 Partial Content
|
|
|
|
const file = await Deno.open(filePath);
|
2022-10-21 21:34:59 +00:00
|
|
|
await file.seek(start, Deno.SeekMode.Start);
|
2023-04-18 07:34:51 +00:00
|
|
|
const sliced = file.readable
|
|
|
|
.pipeThrough(new ByteSliceStream(0, contentLength - 1));
|
2023-11-17 02:26:11 +00:00
|
|
|
const status = STATUS_CODE.PartialContent;
|
|
|
|
return new Response(sliced, {
|
|
|
|
status,
|
|
|
|
statusText: STATUS_TEXT[status],
|
|
|
|
headers,
|
|
|
|
});
|
2022-04-18 02:41:11 +00:00
|
|
|
}
|
2021-07-22 06:12:40 +00:00
|
|
|
|
2023-05-04 04:58:13 +00:00
|
|
|
// Set content length
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ContentLength, `${fileSize}`);
|
2023-05-04 04:58:13 +00:00
|
|
|
|
|
|
|
const file = await Deno.open(filePath);
|
2023-11-17 02:26:11 +00:00
|
|
|
const status = STATUS_CODE.OK;
|
|
|
|
return new Response(file.readable, {
|
|
|
|
status,
|
|
|
|
statusText: STATUS_TEXT[status],
|
|
|
|
headers,
|
|
|
|
});
|
2019-03-08 18:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-02-22 02:06:26 +00:00
|
|
|
async function serveDirIndex(
|
2020-07-14 19:24:17 +00:00
|
|
|
dirPath: string,
|
2021-11-04 10:22:55 +00:00
|
|
|
options: {
|
2023-05-06 07:28:27 +00:00
|
|
|
showDotfiles: boolean;
|
2021-11-04 10:22:55 +00:00
|
|
|
target: string;
|
2023-10-23 06:04:58 +00:00
|
|
|
urlRoot: string | undefined;
|
2023-05-10 06:15:03 +00:00
|
|
|
quiet: boolean | undefined;
|
2021-11-04 10:22:55 +00:00
|
|
|
},
|
2019-03-08 18:04:02 +00:00
|
|
|
): Promise<Response> {
|
2023-05-06 07:28:27 +00:00
|
|
|
const { showDotfiles } = options;
|
2023-10-23 06:04:58 +00:00
|
|
|
const urlRoot = options.urlRoot ? "/" + options.urlRoot : "";
|
2023-06-14 07:37:53 +00:00
|
|
|
const dirUrl = `/${
|
|
|
|
relative(options.target, dirPath).replaceAll(
|
2024-01-18 05:54:39 +00:00
|
|
|
new RegExp(SEPARATOR_PATTERN, "g"),
|
2023-06-14 07:37:53 +00:00
|
|
|
"/",
|
|
|
|
)
|
|
|
|
}`;
|
2023-05-06 08:09:07 +00:00
|
|
|
const listEntryPromise: Promise<EntryInfo>[] = [];
|
2021-02-02 11:01:21 +00:00
|
|
|
|
|
|
|
// if ".." makes sense
|
|
|
|
if (dirUrl !== "/") {
|
2023-06-14 07:37:53 +00:00
|
|
|
const prevPath = join(dirPath, "..");
|
2023-05-06 08:09:07 +00:00
|
|
|
const entryInfo = Deno.stat(prevPath).then((fileInfo): EntryInfo => ({
|
2021-02-02 11:01:21 +00:00
|
|
|
mode: modeToString(true, fileInfo.mode),
|
|
|
|
size: "",
|
|
|
|
name: "../",
|
2023-10-23 06:04:58 +00:00
|
|
|
url: `${urlRoot}${posixJoin(dirUrl, "..")}`,
|
2023-05-06 08:09:07 +00:00
|
|
|
}));
|
|
|
|
listEntryPromise.push(entryInfo);
|
2021-02-02 11:01:21 +00:00
|
|
|
}
|
|
|
|
|
2023-05-06 08:09:07 +00:00
|
|
|
// Read fileInfo in parallel
|
2020-06-12 19:23:38 +00:00
|
|
|
for await (const entry of Deno.readDir(dirPath)) {
|
2021-02-02 19:36:52 +00:00
|
|
|
if (!showDotfiles && entry.name[0] === ".") {
|
|
|
|
continue;
|
|
|
|
}
|
2023-06-14 07:37:53 +00:00
|
|
|
const filePath = join(dirPath, entry.name);
|
2023-08-14 07:08:42 +00:00
|
|
|
const fileUrl = encodeURIComponent(posixJoin(dirUrl, entry.name))
|
2022-09-29 15:02:43 +00:00
|
|
|
.replaceAll("%2F", "/");
|
2023-05-10 06:15:03 +00:00
|
|
|
|
|
|
|
listEntryPromise.push((async () => {
|
|
|
|
try {
|
|
|
|
const fileInfo = await Deno.stat(filePath);
|
|
|
|
return {
|
|
|
|
mode: modeToString(entry.isDirectory, fileInfo.mode),
|
|
|
|
size: entry.isFile ? formatBytes(fileInfo.size ?? 0) : "",
|
|
|
|
name: `${entry.name}${entry.isDirectory ? "/" : ""}`,
|
2023-10-23 06:04:58 +00:00
|
|
|
url: `${urlRoot}${fileUrl}${entry.isDirectory ? "/" : ""}`,
|
2023-05-10 06:15:03 +00:00
|
|
|
};
|
|
|
|
} catch (error) {
|
|
|
|
// Note: Deno.stat for windows system files may be rejected with os error 32.
|
2024-06-25 09:32:34 +00:00
|
|
|
if (!options.quiet) logError(error as Error);
|
2023-05-10 06:15:03 +00:00
|
|
|
return {
|
|
|
|
mode: "(unknown mode)",
|
|
|
|
size: "",
|
|
|
|
name: `${entry.name}${entry.isDirectory ? "/" : ""}`,
|
2023-10-23 06:04:58 +00:00
|
|
|
url: `${urlRoot}${fileUrl}${entry.isDirectory ? "/" : ""}`,
|
2023-05-10 06:15:03 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
})());
|
2018-12-11 22:56:32 +00:00
|
|
|
}
|
2023-05-06 08:09:07 +00:00
|
|
|
|
|
|
|
const listEntry = await Promise.all(listEntryPromise);
|
2019-12-03 00:14:25 +00:00
|
|
|
listEntry.sort((a, b) =>
|
2024-06-25 09:32:34 +00:00
|
|
|
// TODO(iuioiua): Add test to ensure list order is correct
|
2019-12-03 00:14:25 +00:00
|
|
|
a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1
|
2018-12-11 22:56:32 +00:00
|
|
|
);
|
2019-12-03 00:14:25 +00:00
|
|
|
const formattedDirUrl = `${dirUrl.replace(/\/$/, "")}/`;
|
2023-05-06 08:09:07 +00:00
|
|
|
const page = dirViewerTemplate(formattedDirUrl, listEntry);
|
2018-12-11 22:56:32 +00:00
|
|
|
|
2023-05-06 08:58:27 +00:00
|
|
|
const headers = createBaseHeaders();
|
2024-08-06 13:40:47 +00:00
|
|
|
headers.set(HEADER.ContentType, "text/html; charset=UTF-8");
|
2018-12-11 22:56:32 +00:00
|
|
|
|
2023-11-17 02:26:11 +00:00
|
|
|
const status = STATUS_CODE.OK;
|
|
|
|
return new Response(page, {
|
|
|
|
status,
|
|
|
|
statusText: STATUS_TEXT[status],
|
|
|
|
headers,
|
|
|
|
});
|
2018-12-11 22:56:32 +00:00
|
|
|
}
|
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
function serveFallback(maybeError: unknown): Response {
|
|
|
|
if (maybeError instanceof URIError) {
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.BadRequest);
|
2018-12-11 22:56:32 +00:00
|
|
|
}
|
2021-08-31 14:36:30 +00:00
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
if (maybeError instanceof Deno.errors.NotFound) {
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.NotFound);
|
2023-05-06 07:28:27 +00:00
|
|
|
}
|
|
|
|
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.InternalServerError);
|
2018-12-11 22:56:32 +00:00
|
|
|
}
|
|
|
|
|
2022-08-24 01:21:57 +00:00
|
|
|
function serverLog(req: Request, status: number) {
|
2018-12-12 09:38:46 +00:00
|
|
|
const d = new Date().toISOString();
|
|
|
|
const dateFmt = `[${d.slice(0, 10)} ${d.slice(11, 19)}]`;
|
2023-05-06 07:28:27 +00:00
|
|
|
const url = new URL(req.url);
|
|
|
|
const s = `${dateFmt} [${req.method}] ${url.pathname}${url.search} ${status}`;
|
2022-01-07 10:03:20 +00:00
|
|
|
// using console.debug instead of console.log so chrome inspect users can hide request logs
|
|
|
|
console.debug(s);
|
2018-12-12 09:38:46 +00:00
|
|
|
}
|
|
|
|
|
2023-05-06 08:58:27 +00:00
|
|
|
function createBaseHeaders(): Headers {
|
|
|
|
return new Headers({
|
|
|
|
server: "deno",
|
|
|
|
// Set "accept-ranges" so that the client knows it can make range requests on future requests
|
2024-08-06 13:40:47 +00:00
|
|
|
[HEADER.AcceptRanges]: "bytes",
|
2023-05-06 08:58:27 +00:00
|
|
|
});
|
2021-07-22 06:12:40 +00:00
|
|
|
}
|
|
|
|
|
2019-12-03 00:14:25 +00:00
|
|
|
function dirViewerTemplate(dirname: string, entries: EntryInfo[]): string {
|
2021-10-20 08:04:32 +00:00
|
|
|
const paths = dirname.split("/");
|
|
|
|
|
2021-11-03 12:50:00 +00:00
|
|
|
return `
|
2019-12-03 00:14:25 +00:00
|
|
|
<!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 {
|
2022-01-09 01:51:55 +00:00
|
|
|
--background-color: #292929;
|
2019-12-03 00:14:25 +00:00
|
|
|
--color: #fff;
|
|
|
|
}
|
2022-01-09 01:51:55 +00:00
|
|
|
thead {
|
|
|
|
color: #7f7f7f;
|
|
|
|
}
|
2019-12-03 00:14:25 +00:00
|
|
|
}
|
|
|
|
@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;
|
|
|
|
}
|
2022-01-09 01:51:55 +00:00
|
|
|
thead {
|
2019-12-03 00:14:25 +00:00
|
|
|
text-align: left;
|
|
|
|
}
|
2022-01-09 01:51:55 +00:00
|
|
|
thead th {
|
|
|
|
padding-bottom: 12px;
|
|
|
|
}
|
2019-12-03 00:14:25 +00:00
|
|
|
table td {
|
2022-01-09 01:51:55 +00:00
|
|
|
padding: 6px 36px 6px 0px;
|
|
|
|
}
|
|
|
|
.size {
|
|
|
|
text-align: right;
|
|
|
|
padding: 6px 12px 6px 24px;
|
|
|
|
}
|
|
|
|
.mode {
|
|
|
|
font-family: monospace, monospace;
|
2019-12-03 00:14:25 +00:00
|
|
|
}
|
|
|
|
</style>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<main>
|
2021-10-20 08:04:32 +00:00
|
|
|
<h1>Index of
|
|
|
|
<a href="/">home</a>${
|
2021-12-13 15:38:32 +00:00
|
|
|
paths
|
|
|
|
.map((path, index, array) => {
|
|
|
|
if (path === "") return "";
|
|
|
|
const link = array.slice(0, index + 1).join("/");
|
|
|
|
return `<a href="${link}">${path}</a>`;
|
|
|
|
})
|
|
|
|
.join("/")
|
2021-10-20 08:04:32 +00:00
|
|
|
}
|
|
|
|
</h1>
|
2019-12-03 00:14:25 +00:00
|
|
|
<table>
|
2022-01-09 01:51:55 +00:00
|
|
|
<thead>
|
|
|
|
<tr>
|
|
|
|
<th>Mode</th>
|
|
|
|
<th>Size</th>
|
|
|
|
<th>Name</th>
|
|
|
|
</tr>
|
|
|
|
</thead>
|
2020-07-14 19:24:17 +00:00
|
|
|
${
|
2021-12-13 15:38:32 +00:00
|
|
|
entries
|
|
|
|
.map(
|
|
|
|
(entry) => `
|
2020-03-28 17:03:49 +00:00
|
|
|
<tr>
|
|
|
|
<td class="mode">
|
|
|
|
${entry.mode}
|
|
|
|
</td>
|
2022-01-09 01:51:55 +00:00
|
|
|
<td class="size">
|
2020-03-28 17:03:49 +00:00
|
|
|
${entry.size}
|
|
|
|
</td>
|
|
|
|
<td>
|
|
|
|
<a href="${entry.url}">${entry.name}</a>
|
|
|
|
</td>
|
|
|
|
</tr>
|
2020-07-14 19:24:17 +00:00
|
|
|
`,
|
2021-12-13 15:38:32 +00:00
|
|
|
)
|
|
|
|
.join("")
|
2020-07-14 19:24:17 +00:00
|
|
|
}
|
2019-12-03 00:14:25 +00:00
|
|
|
</table>
|
|
|
|
</main>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
`;
|
|
|
|
}
|
|
|
|
|
2022-06-01 14:56:57 +00:00
|
|
|
/** Interface for serveDir options. */
|
|
|
|
export interface ServeDirOptions {
|
2023-05-02 05:24:44 +00:00
|
|
|
/** Serves the files under the given directory root. Defaults to your current directory.
|
|
|
|
*
|
|
|
|
* @default {"."}
|
|
|
|
*/
|
2022-02-22 02:06:26 +00:00
|
|
|
fsRoot?: string;
|
2023-05-02 05:24:44 +00:00
|
|
|
/** Specified that part is stripped from the beginning of the requested pathname.
|
|
|
|
*/
|
2022-02-22 02:06:26 +00:00
|
|
|
urlRoot?: string;
|
2022-11-25 11:40:23 +00:00
|
|
|
/** Enable directory listing.
|
|
|
|
*
|
|
|
|
* @default {false}
|
|
|
|
*/
|
2022-02-22 02:06:26 +00:00
|
|
|
showDirListing?: boolean;
|
2022-11-25 11:40:23 +00:00
|
|
|
/** Serves dotfiles.
|
|
|
|
*
|
|
|
|
* @default {false}
|
|
|
|
*/
|
2022-02-22 02:06:26 +00:00
|
|
|
showDotfiles?: boolean;
|
2024-06-25 09:32:34 +00:00
|
|
|
/** Serves `index.html` as the index file of the directory.
|
2023-05-02 05:24:44 +00:00
|
|
|
*
|
|
|
|
* @default {true}
|
|
|
|
*/
|
2022-10-03 11:09:09 +00:00
|
|
|
showIndex?: boolean;
|
2024-06-25 09:32:34 +00:00
|
|
|
/**
|
|
|
|
* Enable CORS via the
|
|
|
|
* {@linkcode https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin | Access-Control-Allow-Origin}
|
|
|
|
* header.
|
2022-11-25 11:40:23 +00:00
|
|
|
*
|
|
|
|
* @default {false}
|
|
|
|
*/
|
2022-02-22 02:06:26 +00:00
|
|
|
enableCors?: boolean;
|
2024-06-25 09:32:34 +00:00
|
|
|
/** Do not print request level logs.
|
2022-11-25 11:40:23 +00:00
|
|
|
*
|
|
|
|
* @default {false}
|
|
|
|
*/
|
2022-02-22 02:06:26 +00:00
|
|
|
quiet?: boolean;
|
2022-11-25 11:40:23 +00:00
|
|
|
/** The algorithm to use for generating the ETag.
|
|
|
|
*
|
2023-04-13 09:43:43 +00:00
|
|
|
* @default {"SHA-256"}
|
2022-11-25 11:40:23 +00:00
|
|
|
*/
|
2023-04-13 09:43:43 +00:00
|
|
|
etagAlgorithm?: AlgorithmIdentifier;
|
2023-01-29 06:41:28 +00:00
|
|
|
/** Headers to add to each response
|
2022-12-27 04:43:04 +00:00
|
|
|
*
|
|
|
|
* @default {[]}
|
|
|
|
*/
|
|
|
|
headers?: string[];
|
2022-02-22 02:06:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Serves the files under the given directory root (opts.fsRoot).
|
|
|
|
*
|
2024-05-22 19:09:08 +00:00
|
|
|
* @example Usage
|
|
|
|
* ```ts no-eval
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { serveDir } from "@std/http/file-server";
|
2022-02-22 02:06:26 +00:00
|
|
|
*
|
2023-07-21 03:29:01 +00:00
|
|
|
* Deno.serve((req) => {
|
2022-02-22 02:06:26 +00:00
|
|
|
* const pathname = new URL(req.url).pathname;
|
|
|
|
* if (pathname.startsWith("/static")) {
|
|
|
|
* return serveDir(req, {
|
|
|
|
* fsRoot: "path/to/static/files/dir",
|
|
|
|
* });
|
|
|
|
* }
|
|
|
|
* // Do dynamic responses
|
|
|
|
* return new Response();
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
2024-06-25 09:32:34 +00:00
|
|
|
* @example Changing the URL root
|
|
|
|
*
|
|
|
|
* Requests to `/static/path/to/file` will be served from `./public/path/to/file`.
|
2022-02-22 02:06:26 +00:00
|
|
|
*
|
2024-05-22 19:09:08 +00:00
|
|
|
* ```ts no-eval
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { serveDir } from "@std/http/file-server";
|
2022-02-22 02:06:26 +00:00
|
|
|
*
|
2024-06-25 09:32:34 +00:00
|
|
|
* Deno.serve((req) => serveDir(req, {
|
2022-02-22 02:06:26 +00:00
|
|
|
* fsRoot: "public",
|
|
|
|
* urlRoot: "static",
|
2024-06-25 09:32:34 +00:00
|
|
|
* }));
|
2022-02-22 02:06:26 +00:00
|
|
|
* ```
|
|
|
|
*
|
2022-06-01 14:56:57 +00:00
|
|
|
* @param req The request to handle
|
2024-05-22 19:09:08 +00:00
|
|
|
* @param opts Additional options.
|
|
|
|
* @returns A response for the request.
|
2022-02-22 02:06:26 +00:00
|
|
|
*/
|
2023-12-19 00:26:13 +00:00
|
|
|
export async function serveDir(
|
|
|
|
req: Request,
|
|
|
|
opts: ServeDirOptions = {},
|
|
|
|
): Promise<Response> {
|
2024-08-10 18:42:34 +00:00
|
|
|
if (req.method !== METHOD.Get) {
|
2024-08-07 12:35:30 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.MethodNotAllowed);
|
|
|
|
}
|
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
let response: Response;
|
2022-02-22 02:06:26 +00:00
|
|
|
try {
|
2023-05-06 07:28:27 +00:00
|
|
|
response = await createServeDirResponse(req, opts);
|
|
|
|
} catch (error) {
|
2024-06-25 09:32:34 +00:00
|
|
|
if (!opts.quiet) logError(error as Error);
|
2023-05-06 07:28:27 +00:00
|
|
|
response = serveFallback(error);
|
2022-02-22 02:06:26 +00:00
|
|
|
}
|
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
// Do not update the header if the response is a 301 redirect.
|
2023-05-07 06:48:39 +00:00
|
|
|
const isRedirectResponse = isRedirectStatus(response.status);
|
2023-05-06 07:28:27 +00:00
|
|
|
|
|
|
|
if (opts.enableCors && !isRedirectResponse) {
|
2024-08-06 13:40:47 +00:00
|
|
|
response.headers.append(HEADER.AccessControlAllowOrigin, "*");
|
2022-02-22 02:06:26 +00:00
|
|
|
response.headers.append(
|
2024-08-06 13:40:47 +00:00
|
|
|
HEADER.AccessControlAllowHeaders,
|
2022-02-22 02:06:26 +00:00
|
|
|
"Origin, X-Requested-With, Content-Type, Accept, Range",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
if (!opts.quiet) serverLog(req, response.status);
|
2022-02-22 02:06:26 +00:00
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
if (opts.headers && !isRedirectResponse) {
|
2022-12-27 04:43:04 +00:00
|
|
|
for (const header of opts.headers) {
|
|
|
|
const headerSplit = header.split(":");
|
2024-02-15 21:07:19 +00:00
|
|
|
const name = headerSplit[0]!;
|
2022-12-27 04:43:04 +00:00
|
|
|
const value = headerSplit.slice(1).join(":");
|
|
|
|
response.headers.append(name, value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
return response;
|
2022-02-22 02:06:26 +00:00
|
|
|
}
|
|
|
|
|
2023-05-06 07:28:27 +00:00
|
|
|
async function createServeDirResponse(
|
|
|
|
req: Request,
|
|
|
|
opts: ServeDirOptions,
|
|
|
|
) {
|
|
|
|
const target = opts.fsRoot || ".";
|
|
|
|
const urlRoot = opts.urlRoot;
|
|
|
|
const showIndex = opts.showIndex ?? true;
|
|
|
|
const showDotfiles = opts.showDotfiles || false;
|
2023-05-10 06:15:03 +00:00
|
|
|
const { etagAlgorithm, showDirListing, quiet } = opts;
|
2023-05-06 07:28:27 +00:00
|
|
|
|
|
|
|
const url = new URL(req.url);
|
|
|
|
const decodedUrl = decodeURIComponent(url.pathname);
|
2023-08-14 07:08:42 +00:00
|
|
|
let normalizedPath = posixNormalize(decodedUrl);
|
2023-05-06 07:28:27 +00:00
|
|
|
|
|
|
|
if (urlRoot && !normalizedPath.startsWith("/" + urlRoot)) {
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.NotFound);
|
2023-05-06 07:28:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Redirect paths like `/foo////bar` and `/foo/bar/////` to normalized paths.
|
|
|
|
if (normalizedPath !== decodedUrl) {
|
|
|
|
url.pathname = normalizedPath;
|
|
|
|
return Response.redirect(url, 301);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (urlRoot) {
|
|
|
|
normalizedPath = normalizedPath.replace(urlRoot, "");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove trailing slashes to avoid ENOENT errors
|
|
|
|
// when accessing a path to a file with a trailing slash.
|
|
|
|
if (normalizedPath.endsWith("/")) {
|
|
|
|
normalizedPath = normalizedPath.slice(0, -1);
|
|
|
|
}
|
|
|
|
|
2023-06-14 07:37:53 +00:00
|
|
|
const fsPath = join(target, normalizedPath);
|
2023-05-06 07:28:27 +00:00
|
|
|
const fileInfo = await Deno.stat(fsPath);
|
|
|
|
|
|
|
|
// For files, remove the trailing slash from the path.
|
|
|
|
if (fileInfo.isFile && url.pathname.endsWith("/")) {
|
|
|
|
url.pathname = url.pathname.slice(0, -1);
|
|
|
|
return Response.redirect(url, 301);
|
|
|
|
}
|
|
|
|
// For directories, the path must have a trailing slash.
|
|
|
|
if (fileInfo.isDirectory && !url.pathname.endsWith("/")) {
|
|
|
|
// On directory listing pages,
|
|
|
|
// if the current URL's pathname doesn't end with a slash, any
|
|
|
|
// relative URLs in the index file will resolve against the parent
|
|
|
|
// directory, rather than the current directory. To prevent that, we
|
|
|
|
// return a 301 redirect to the URL with a slash.
|
|
|
|
url.pathname += "/";
|
|
|
|
return Response.redirect(url, 301);
|
|
|
|
}
|
|
|
|
|
|
|
|
// if target is file, serve file.
|
|
|
|
if (!fileInfo.isDirectory) {
|
2023-05-07 06:48:39 +00:00
|
|
|
return serveFile(req, fsPath, {
|
2023-05-06 07:28:27 +00:00
|
|
|
etagAlgorithm,
|
|
|
|
fileInfo,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// if target is directory, serve index or dir listing.
|
|
|
|
if (showIndex) { // serve index.html
|
2023-06-14 07:37:53 +00:00
|
|
|
const indexPath = join(fsPath, "index.html");
|
2023-05-06 07:28:27 +00:00
|
|
|
|
|
|
|
let indexFileInfo: Deno.FileInfo | undefined;
|
|
|
|
try {
|
|
|
|
indexFileInfo = await Deno.lstat(indexPath);
|
|
|
|
} catch (error) {
|
|
|
|
if (!(error instanceof Deno.errors.NotFound)) {
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
// skip Not Found error
|
|
|
|
}
|
|
|
|
|
|
|
|
if (indexFileInfo?.isFile) {
|
2023-05-07 06:48:39 +00:00
|
|
|
return serveFile(req, indexPath, {
|
2023-05-06 07:28:27 +00:00
|
|
|
etagAlgorithm,
|
|
|
|
fileInfo: indexFileInfo,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (showDirListing) { // serve directory list
|
2023-10-23 06:04:58 +00:00
|
|
|
return serveDirIndex(fsPath, { urlRoot, showDotfiles, target, quiet });
|
2023-05-06 07:28:27 +00:00
|
|
|
}
|
|
|
|
|
2023-11-17 02:26:11 +00:00
|
|
|
return createStandardResponse(STATUS_CODE.NotFound);
|
2020-10-26 13:55:26 +00:00
|
|
|
}
|
|
|
|
|
2024-06-25 09:32:34 +00:00
|
|
|
function logError(error: Error) {
|
|
|
|
console.error(`%c${error.message}`, "color: red");
|
2023-05-10 06:15:03 +00:00
|
|
|
}
|
|
|
|
|
2022-08-24 01:21:57 +00:00
|
|
|
function main() {
|
2023-11-16 02:08:51 +00:00
|
|
|
const serverArgs = parseArgs(Deno.args, {
|
2022-12-27 04:43:04 +00:00
|
|
|
string: ["port", "host", "cert", "key", "header"],
|
2022-11-11 05:08:35 +00:00
|
|
|
boolean: ["help", "dir-listing", "dotfiles", "cors", "verbose", "version"],
|
2022-06-09 04:06:36 +00:00
|
|
|
negatable: ["dir-listing", "dotfiles", "cors"],
|
2022-12-27 04:43:04 +00:00
|
|
|
collect: ["header"],
|
2021-11-04 10:22:55 +00:00
|
|
|
default: {
|
|
|
|
"dir-listing": true,
|
2021-12-13 15:38:32 +00:00
|
|
|
dotfiles: true,
|
|
|
|
cors: true,
|
2022-04-18 02:41:11 +00:00
|
|
|
verbose: false,
|
2022-11-11 05:08:35 +00:00
|
|
|
version: false,
|
2021-12-13 15:38:32 +00:00
|
|
|
host: "0.0.0.0",
|
2024-06-24 04:57:37 +00:00
|
|
|
port: undefined,
|
2021-12-13 15:38:32 +00:00
|
|
|
cert: "",
|
|
|
|
key: "",
|
2021-11-04 10:22:55 +00:00
|
|
|
},
|
|
|
|
alias: {
|
|
|
|
p: "port",
|
|
|
|
c: "cert",
|
|
|
|
k: "key",
|
|
|
|
h: "help",
|
2022-04-18 02:41:11 +00:00
|
|
|
v: "verbose",
|
2022-11-11 05:08:35 +00:00
|
|
|
V: "version",
|
2022-12-27 04:43:04 +00:00
|
|
|
H: "header",
|
2021-11-04 10:22:55 +00:00
|
|
|
},
|
2022-04-18 02:41:11 +00:00
|
|
|
});
|
2024-06-24 04:57:37 +00:00
|
|
|
const port = serverArgs.port ? Number(serverArgs.port) : undefined;
|
2022-12-27 04:43:04 +00:00
|
|
|
const headers = serverArgs.header || [];
|
2021-11-03 15:02:41 +00:00
|
|
|
const host = serverArgs.host;
|
|
|
|
const certFile = serverArgs.cert;
|
|
|
|
const keyFile = serverArgs.key;
|
2020-08-12 10:55:38 +00:00
|
|
|
|
2021-11-04 10:22:55 +00:00
|
|
|
if (serverArgs.help) {
|
|
|
|
printUsage();
|
|
|
|
Deno.exit();
|
|
|
|
}
|
|
|
|
|
2022-11-11 05:08:35 +00:00
|
|
|
if (serverArgs.version) {
|
2024-04-29 02:57:30 +00:00
|
|
|
console.log(`Deno File Server ${denoConfig.version}`);
|
2022-11-11 05:08:35 +00:00
|
|
|
Deno.exit();
|
|
|
|
}
|
|
|
|
|
2021-08-31 14:36:30 +00:00
|
|
|
if (keyFile || certFile) {
|
|
|
|
if (keyFile === "" || certFile === "") {
|
2020-08-12 10:55:38 +00:00
|
|
|
console.log("--key and --cert are required for TLS");
|
2021-11-04 10:22:55 +00:00
|
|
|
printUsage();
|
|
|
|
Deno.exit(1);
|
2020-08-12 10:55:38 +00:00
|
|
|
}
|
|
|
|
}
|
2020-06-03 17:48:03 +00:00
|
|
|
|
2022-04-18 02:41:11 +00:00
|
|
|
const wild = serverArgs._ as string[];
|
2023-06-06 05:00:05 +00:00
|
|
|
const target = resolve(wild[0] ?? "");
|
2020-06-03 17:48:03 +00:00
|
|
|
|
2022-02-22 02:06:26 +00:00
|
|
|
const handler = (req: Request): Promise<Response> => {
|
|
|
|
return serveDir(req, {
|
|
|
|
fsRoot: target,
|
|
|
|
showDirListing: serverArgs["dir-listing"],
|
|
|
|
showDotfiles: serverArgs.dotfiles,
|
|
|
|
enableCors: serverArgs.cors,
|
2022-04-18 02:41:11 +00:00
|
|
|
quiet: !serverArgs.verbose,
|
2022-12-27 04:43:04 +00:00
|
|
|
headers,
|
2022-02-22 02:06:26 +00:00
|
|
|
});
|
2020-08-12 10:55:38 +00:00
|
|
|
};
|
2018-11-07 18:16:07 +00:00
|
|
|
|
2022-06-21 06:36:51 +00:00
|
|
|
const useTls = !!(keyFile && certFile);
|
2021-08-31 14:36:30 +00:00
|
|
|
|
2024-04-22 05:25:14 +00:00
|
|
|
function onListen({ port, hostname }: { port: number; hostname: string }) {
|
2024-07-25 10:13:16 +00:00
|
|
|
let networkAddress: string | undefined = undefined;
|
|
|
|
if (
|
|
|
|
Deno.permissions.querySync({ name: "sys", kind: "networkInterfaces" })
|
|
|
|
.state === "granted"
|
|
|
|
) {
|
|
|
|
networkAddress = getNetworkAddress();
|
|
|
|
}
|
2024-04-22 05:25:14 +00:00
|
|
|
const protocol = useTls ? "https" : "http";
|
|
|
|
let message = `Listening on:\n- Local: ${protocol}://${hostname}:${port}`;
|
|
|
|
if (networkAddress && !DENO_DEPLOYMENT_ID) {
|
|
|
|
message += `\n- Network: ${protocol}://${networkAddress}:${port}`;
|
|
|
|
}
|
|
|
|
console.log(message);
|
|
|
|
}
|
|
|
|
|
2022-02-22 02:06:26 +00:00
|
|
|
if (useTls) {
|
2023-07-21 03:29:01 +00:00
|
|
|
Deno.serve({
|
2022-06-21 06:36:51 +00:00
|
|
|
port,
|
2021-12-13 15:38:32 +00:00
|
|
|
hostname: host,
|
2024-04-22 05:25:14 +00:00
|
|
|
onListen,
|
2023-07-21 03:29:01 +00:00
|
|
|
cert: Deno.readTextFileSync(certFile),
|
|
|
|
key: Deno.readTextFileSync(keyFile),
|
|
|
|
}, handler);
|
2020-08-12 10:55:38 +00:00
|
|
|
} else {
|
2023-07-21 03:29:01 +00:00
|
|
|
Deno.serve({
|
|
|
|
port,
|
|
|
|
hostname: host,
|
2024-04-22 05:25:14 +00:00
|
|
|
onListen,
|
2023-07-21 03:29:01 +00:00
|
|
|
}, handler);
|
2020-08-12 10:55:38 +00:00
|
|
|
}
|
2020-04-01 16:51:01 +00:00
|
|
|
}
|
|
|
|
|
2021-11-04 10:22:55 +00:00
|
|
|
function printUsage() {
|
2024-04-29 02:57:30 +00:00
|
|
|
console.log(`Deno File Server ${denoConfig.version}
|
2021-11-04 10:22:55 +00:00
|
|
|
Serves a local directory in HTTP.
|
|
|
|
|
|
|
|
INSTALL:
|
2024-06-24 04:57:37 +00:00
|
|
|
deno install --allow-net --allow-read --allow-sys jsr:@std/http@${denoConfig.version}/file-server
|
2021-11-04 10:22:55 +00:00
|
|
|
|
|
|
|
USAGE:
|
|
|
|
file_server [path] [options]
|
|
|
|
|
|
|
|
OPTIONS:
|
2022-12-27 04:43:04 +00:00
|
|
|
-h, --help Prints help information
|
2024-06-24 04:57:37 +00:00
|
|
|
-p, --port <PORT> Set port (default is 8000)
|
2022-12-27 04:43:04 +00:00
|
|
|
--cors Enable CORS via the "Access-Control-Allow-Origin" header
|
|
|
|
--host <HOST> Hostname (default is 0.0.0.0)
|
|
|
|
-c, --cert <FILE> TLS certificate file (enables TLS)
|
|
|
|
-k, --key <FILE> TLS key file (enables TLS)
|
|
|
|
-H, --header <HEADER> Sets a header on every request.
|
|
|
|
(e.g. --header "Cache-Control: no-cache")
|
|
|
|
This option can be specified multiple times.
|
|
|
|
--no-dir-listing Disable directory listing
|
|
|
|
--no-dotfiles Do not show dotfiles
|
|
|
|
--no-cors Disable cross-origin resource sharing
|
|
|
|
-v, --verbose Print request level logs
|
|
|
|
-V, --version Print version information
|
2021-11-04 10:22:55 +00:00
|
|
|
|
|
|
|
All TLS options are required when one is provided.`);
|
|
|
|
}
|
|
|
|
|
2020-04-01 16:51:01 +00:00
|
|
|
if (import.meta.main) {
|
|
|
|
main();
|
|
|
|
}
|