跳至主要内容

文件服务器

概念

  • 使用 Deno.open 以块的形式读取文件内容。
  • 将 Deno 文件转换为 ReadableStream
  • 使用 Deno 集成的 HTTP 服务器运行您自己的文件服务器。

概述

通过网络发送文件是一个常见的需求。正如 获取数据示例 中所见,由于文件可以是任何大小,因此使用流来防止将整个文件加载到内存中非常重要。

示例

命令: deno run --allow-read=. --allow-net file_server.ts

// Start listening on port 8080 of localhost.
const server = Deno.listen({ port: 8080 });
console.log("File server running on https://127.0.0.1:8080/");

for await (const conn of server) {
handleHttp(conn).catch(console.error);
}

async function handleHttp(conn: Deno.Conn) {
const httpConn = Deno.serveHttp(conn);
for await (const requestEvent of httpConn) {
// Use the request pathname as filepath
const url = new URL(requestEvent.request.url);
const filepath = decodeURIComponent(url.pathname);

// Try opening the file
let file;
try {
file = await Deno.open("." + filepath, { read: true });
} catch {
// If the file cannot be opened, return a "404 Not Found" response
const notFoundResponse = new Response("404 Not Found", { status: 404 });
await requestEvent.respondWith(notFoundResponse);
continue;
}

// Build a readable stream so the file doesn't have to be fully loaded into
// memory while we send it
const readableStream = file.readable;

// Build and send the response
const response = new Response(readableStream);
await requestEvent.respondWith(response);
}
}

使用 std/http 文件服务器

Deno 标准库提供了一个 文件服务器,因此您无需自己编写。

要使用它,首先将远程脚本安装到本地文件系统。这会将脚本安装到 Deno 安装根目录的 bin 目录,例如 /home/alice/.deno/bin/file_server

deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts

现在,您可以使用简化的脚本名称运行该脚本。运行它

$ file_server .
Downloading https://deno.land/std/http/file_server.ts...
[...]
HTTP server listening on http://0.0.0.0:4507/

现在,在您的网络浏览器中访问 http://0.0.0.0:4507/,以查看您的本地目录内容。

完整的选项列表可通过以下方式获得

file_server --help

示例输出

Deno File Server
Serves a local directory in HTTP.
INSTALL:
deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts
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
--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)
--no-dir-listing Disable directory listing
All TLS options are required when one is provided.