乐闻世界logo
搜索文章和话题

What are the common modules in Deno's standard library?

2月21日 16:08

Deno's Standard Library is a carefully designed, tested, and maintained set of modules that provide developers with high-quality, reusable code. The standard library covers everything from file system operations to network programming and is an important part of the Deno ecosystem.

Standard Library Overview

The Deno standard library is hosted at https://deno.land/std/. All modules undergo rigorous code review and testing to ensure code quality and security.

Version Management

The standard library uses semantic versioning. It's recommended to specify the version when importing:

typescript
// Recommended: Specify version import { serve } from "https://deno.land/std@0.208.0/http/server.ts"; // Not recommended: Use latest version import { serve } from "https://deno.land/std/http/server.ts";

Main Modules

1. HTTP Module

HTTP Server

typescript
import { 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 Client

typescript
import { 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. File System Module

File Operations

typescript
import { ensureDir, ensureFile } from "https://deno.land/std@0.208.0/fs/mod.ts"; // Ensure directory exists await ensureDir("./data/uploads"); // Ensure file exists await ensureFile("./config.json"); // Copy file import { copy } from "https://deno.land/std@0.208.0/fs/copy.ts"; await copy("source.txt", "destination.txt"); // Move file import { move } from "https://deno.land/std@0.208.0/fs/move.ts"; await move("old.txt", "new.txt");

Directory Traversal

typescript
import { 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. Path Module

typescript
import { 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")); // Absolute path

4. Encoding Module

Base64 Encoding

typescript
import { 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 Encoding

typescript
import { 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. Testing Module

typescript
import { 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. Logging Module

typescript
import { 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 Module

typescript
import { v4 as uuidv4, v5 as uuidv5 } from "https://deno.land/std@0.208.0/uuid/mod.ts"; const id1 = uuidv4(); console.log(id1); // Generate random UUID const id2 = uuidv5("hello", uuidv4()); console.log(id2); // Generate UUID based on namespace

8. Date Time Module

typescript
import { 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 object

9. Colors Module

typescript
import { 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. Async Module

typescript
import { delay, retry } from "https://deno.land/std@0.208.0/async/mod.ts"; // Delay execution await delay(1000); // Wait 1 second // Retry mechanism 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. Streams Module

typescript
import { 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. Command Line Module

typescript
import { 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); // Run: deno run script.ts --verbose --output=result.txt // Output: { _: [], verbose: true, help: false, output: "result.txt" }

Practical Application Examples

File Upload Server

typescript
import { 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 });

Logging System

typescript
import { 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; } }

Standard Library Advantages

  1. High-quality code: All modules undergo rigorous review and testing
  2. Type-safe: Complete TypeScript type definitions
  3. Well-documented: Detailed API documentation and examples
  4. Regular updates: Continuous maintenance and feature enhancements
  5. Consistency: Unified code style and API design
  6. Secure and reliable: Security audited with no known vulnerabilities

Best Practices

  1. Specify versions: Always use specific versions of the standard library
  2. Prioritize usage: Use standard library over third-party libraries when possible
  3. Check documentation: Use deno doc to view module documentation
  4. Contribute code: Submit PRs to contribute code when issues are found
  5. Stay updated: Regularly check the standard library changelog

The Deno standard library provides developers with powerful and reliable infrastructure, greatly simplifying the implementation of common tasks, and is an important pillar of the Deno ecosystem.

标签:Deno