檔案伺服器
概念
- 使用 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.