Deno 的标准库(Standard Library)是一组经过精心设计、测试和维护的模块,为开发者提供了高质量、可复用的代码。标准库涵盖了从文件系统操作到网络编程的各个方面,是 Deno 生态系统的重要组成部分。
标准库概述
Deno 标准库托管在 https://deno.land/std/,所有模块都经过严格的代码审查和测试,确保代码质量和安全性。
版本管理
标准库使用语义化版本控制,建议在导入时指定版本:
typescript// 推荐:指定版本 import { serve } from "https://deno.land/std@0.208.0/http/server.ts"; // 不推荐:使用最新版本 import { serve } from "https://deno.land/std/http/server.ts";
主要模块
1. HTTP 模块
HTTP 服务器
typescriptimport { serve } from "https://deno.land/std@0.208.0/http/server.ts"; const handler = async (req: Request): Promise<Response> => { const url = new URL(req.url); if (url.pathname === "/") { return new Response("Hello, Deno!", { headers: { "content-type": "text/plain" }, }); } return new Response("Not Found", { status: 404 }); }; await serve(handler, { port: 8000 });
HTTP 客户端
typescriptimport { fetch } from "https://deno.land/std@0.208.0/http/fetch.ts"; const response = await fetch("https://api.example.com/data"); const data = await response.json(); console.log(data);
2. 文件系统模块
文件操作
typescriptimport { ensureDir, ensureFile } from "https://deno.land/std@0.208.0/fs/mod.ts"; // 确保目录存在 await ensureDir("./data/uploads"); // 确保文件存在 await ensureFile("./config.json"); // 复制文件 import { copy } from "https://deno.land/std@0.208.0/fs/copy.ts"; await copy("source.txt", "destination.txt"); // 移动文件 import { move } from "https://deno.land/std@0.208.0/fs/move.ts"; await move("old.txt", "new.txt");
遍历目录
typescriptimport { walk } from "https://deno.land/std@0.208.0/fs/walk.ts"; for await (const entry of walk("./src")) { console.log(entry.path); if (entry.isFile) { console.log(`File: ${entry.name}`); } else if (entry.isDirectory) { console.log(`Directory: ${entry.name}`); } }
3. 路径模块
typescriptimport { join, basename, dirname, extname, resolve } from "https://deno.land/std@0.208.0/path/mod.ts"; const path = "/home/user/documents/file.txt"; console.log(basename(path)); // "file.txt" console.log(dirname(path)); // "/home/user/documents" console.log(extname(path)); // ".txt" console.log(join("/home", "user", "docs")); // "/home/user/docs" console.log(resolve("./src", "file.ts")); // 绝对路径
4. 编码模块
Base64 编码
typescriptimport { encodeBase64, decodeBase64 } from "https://deno.land/std@0.208.0/encoding/base64.ts"; const text = "Hello, Deno!"; const encoded = encodeBase64(text); console.log(encoded); // "SGVsbG8sIERlbm8h" const decoded = decodeBase64(encoded); console.log(decoded); // "Hello, Deno!"
Hex 编码
typescriptimport { encodeHex, decodeHex } from "https://deno.land/std@0.208.0/encoding/hex.ts"; const data = new TextEncoder().encode("Hello"); const hex = encodeHex(data); console.log(hex); // "48656c6c6f" const decoded = decodeHex(hex); console.log(new TextDecoder().decode(decoded)); // "Hello"
5. 测试模块
typescriptimport { assertEquals, assertThrows } from "https://deno.land/std@0.208.0/testing/asserts.ts"; Deno.test("assertEquals example", () => { assertEquals(1 + 1, 2); assertEquals("hello", "hello"); }); Deno.test("assertThrows example", () => { assertThrows( () => { throw new Error("Test error"); }, Error, "Test error" ); });
6. 日志模块
typescriptimport { getLogger, setup, handlers } from "https://deno.land/std@0.208.0/log/mod.ts"; await setup({ handlers: { console: new handlers.ConsoleHandler("INFO"), }, loggers: { default: { level: "INFO", handlers: ["console"], }, }, }); const logger = getLogger(); logger.info("Application started"); logger.warning("This is a warning"); logger.error("An error occurred");
7. UUID 模块
typescriptimport { v4 as uuidv4, v5 as uuidv5 } from "https://deno.land/std@0.208.0/uuid/mod.ts"; const id1 = uuidv4(); console.log(id1); // 生成随机 UUID const id2 = uuidv5("hello", uuidv4()); console.log(id2); // 基于命名空间生成 UUID
8. 日期时间模块
typescriptimport { format, parse } from "https://deno.land/std@0.208.0/datetime/mod.ts"; const now = new Date(); const formatted = format(now, "yyyy-MM-dd HH:mm:ss"); console.log(formatted); // "2024-01-15 10:30:45" const parsed = parse("2024-01-15", "yyyy-MM-dd"); console.log(parsed); // Date 对象
9. 颜色模块
typescriptimport { red, green, blue, bold } from "https://deno.land/std@0.208.0/fmt/colors.ts"; console.log(red("Error message")); console.log(green("Success message")); console.log(blue("Info message")); console.log(bold("Important message"));
10. 异步模块
typescriptimport { delay, retry } from "https://deno.land/std@0.208.0/async/mod.ts"; // 延迟执行 await delay(1000); // 等待 1 秒 // 重试机制 const result = await retry(async () => { const response = await fetch("https://api.example.com"); if (!response.ok) throw new Error("Request failed"); return response.json(); }, { maxAttempts: 3, minTimeout: 1000, });
11. 流模块
typescriptimport { copy } from "https://deno.land/std@0.208.0/streams/copy.ts"; const file = await Deno.open("input.txt"); const output = await Deno.open("output.txt", { create: true, write: true }); await copy(file, output); file.close(); output.close();
12. 命令行模块
typescriptimport { parseArgs } from "https://deno.land/std@0.208.0/cli/parse_args.ts"; const args = parseArgs(Deno.args, { boolean: ["verbose", "help"], string: ["output"], default: { verbose: false }, }); console.log(args); // 运行: deno run script.ts --verbose --output=result.txt // 输出: { _: [], verbose: true, help: false, output: "result.txt" }
实际应用示例
文件上传服务器
typescriptimport { serve } from "https://deno.land/std@0.208.0/http/server.ts"; import { ensureDir } from "https://deno.land/std@0.208.0/fs/mod.ts"; import { extname } from "https://deno.land/std@0.208.0/path/mod.ts"; const UPLOAD_DIR = "./uploads"; await ensureDir(UPLOAD_DIR); const handler = async (req: Request): Promise<Response> => { const url = new URL(req.url); if (req.method === "POST" && url.pathname === "/upload") { const formData = await req.formData(); const file = formData.get("file") as File; if (file) { const filename = `${crypto.randomUUID()}${extname(file.name)}`; const filepath = `${UPLOAD_DIR}/${filename}`; const content = await file.arrayBuffer(); await Deno.writeFile(filepath, new Uint8Array(content)); return new Response(JSON.stringify({ filename }), { headers: { "Content-Type": "application/json" }, }); } } return new Response("Not Found", { status: 404 }); }; await serve(handler, { port: 8000 });
日志记录系统
typescriptimport { getLogger, setup, handlers, LogRecord } from "https://deno.land/std@0.208.0/log/mod.ts"; class CustomHandler extends handlers.BaseHandler { override format(logRecord: LogRecord): string { const { levelName, msg, datetime } = logRecord; return `[${datetime.toISOString()}] [${levelName}] ${msg}`; } } await setup({ handlers: { console: new CustomHandler("DEBUG"), }, loggers: { default: { level: "DEBUG", handlers: ["console"], }, }, }); const logger = getLogger(); async function processData(data: any) { logger.debug(`Processing data: ${JSON.stringify(data)}`); try { const result = await performOperation(data); logger.info("Operation completed successfully"); return result; } catch (error) { logger.error(`Operation failed: ${error.message}`); throw error; } }
标准库的优势
- 高质量代码:所有模块都经过严格审查和测试
- 类型安全:完整的 TypeScript 类型定义
- 文档完善:详细的 API 文档和示例
- 定期更新:持续维护和功能增强
- 一致性:统一的代码风格和 API 设计
- 安全可靠:经过安全审计,无已知漏洞
最佳实践
- 指定版本:始终使用特定版本的标准库
- 优先使用:在可能的情况下优先使用标准库而非第三方库
- 查看文档:使用
deno doc查看模块文档 - 贡献代码:发现问题时可以提交 PR 贡献代码
- 关注更新:定期查看标准库的更新日志
Deno 标准库为开发者提供了强大而可靠的基础设施,大大简化了常见任务的实现,是 Deno 生态系统的重要支柱。