Lesson 15-Deno Commonly Used Basic Modules and Standard Library

Deno’s standard library (std/) provides a rich set of out-of-the-box modules, adhering to modern JavaScript/TypeScript best practices. Below is a categorized overview of core modules and their functionalities:

Core Foundation Modules

File System Operations (std/fs)

ModuleFunctionalityExample
fs/read_file.tsRead file contentconst text = await Deno.readTextFile("file.txt")
fs/write_file.tsWrite to fileawait Deno.writeTextFile("file.txt", "Hello")
fs/copy.tsCopy files/directoriesawait copy("src/", "dest/", { overwrite: true })
fs/ensure_file.tsEnsure file existsawait ensureFile("data.json")
fs/exists.tsCheck if path existsconst exists = await exists("file.txt")

Features:

  • All operations require explicit --allow-read/--allow-write permissions.
  • Supports Promise-based asynchronous APIs.
  • Provides atomic operations (e.g., copy with overwrite option).

Network Requests (std/http)

ModuleFunctionalityExample
http/server.tsCreate HTTP serverconst server = serve({ port: 8000 })
http/client.tsSend HTTP requestsconst resp = await fetch("https://api.example.com")
http/cookie.tsCookie parsing utilityparseCookies(req.headers)

Typical Usage:

// Create a basic HTTP server
import { serve } from "std/http/server.ts";
const server = serve({ port: 8000 });
for await (const req of server) {
  req.respond({ body: "Hello Deno!" });
}

Path Handling (std/path)

ModuleFunctionalityExample
path/mod.tsCross-platform path operationsjoin("dir", "file.txt")"dir/file.txt"
path/win32.tsWindows-specific path handlingnormalize("C:\\dir\\..\\file")

Key Functions:

  • join(...paths): Smart path concatenation.
  • basename(path): Extract filename.
  • extname(path): Extract file extension.

Advanced Functionality Modules

Data Parsing (std/encoding)

ModuleFunctionalityExample
encoding/json.tsJSON encoding/decodingconst obj = JSON.parse('{"a":1}')
encoding/base64.tsBase64 conversionencode("text") / decode("dGV4dA==")
encoding/csv.tsCSV parsingparseCsv("a,b\nc,d")

Notes:

  • JSON operations use the global JSON object (consistent with browsers).
  • Base64 supports URL-safe mode.

Date and Time (std/datetime)

ModuleFunctionalityExample
datetime/mod.tsDate formattingformat(new Date(), "yyyy-MM-dd")
datetime/iso8601.tsISO8601 parsingparseIso8601("2023-01-01T00:00:00Z")

Unique Features:

  • Supports multiple date parsing formats.
  • Time zone conversion utilities.

Logging System (std/log)

ModuleFunctionalityExample
log/mod.tsMulti-level logginglogger.info("User login")
log/levels.tsLog level controllogger.setLevel("DEBUG")

Log Levels:

  • DEBUG | INFO | WARNING | ERROR | CRITICAL

Utility Modules

Testing Framework (std/testing)

ModuleFunctionalityExample
testing/asserts.tsAssertion libraryassertEquals(1, 1)
testing/bench.tsBenchmark testingbench(() => heavyTask())

Assertion Methods:

  • assertEquals(actual, expected)
  • assertThrows(fn, ErrorClass?)

Random Number Generation (std/random)

ModuleFunctionalityExample
random/mod.tsSecure random numbersrandomBytes(32)
random/uuid.tsUUID generationuuidv4()

Security Note:

  • randomBytes uses OS-level cryptographically secure APIs.
  • Suitable for generating keys, tokens, and other sensitive data.

Signal Handling (std/signal)

ModuleFunctionalityExample
signal/mod.tsProcess signal listeningonSignal("SIGTERM", () => cleanup())

Supported Signals:

  • SIGINT (Ctrl+C)
  • SIGTERM (Graceful termination)

Web Utilities (std/web)

ModuleFunctionalityExample
web/cookie.tsCookie operationsserializeCookie("name", "value")
web/storage.tsWeb Storage simulationsessionStorage.set("key", "value")

Use Cases:

  • Frontend compatibility in Deno Deploy environments.
  • Server-side simulation of browser APIs.

Best Practices for Module Usage

Centralized Dependency Management (deps.ts)

// deps.ts
export { serve } from "https://deno.land/std@0.140.0/http/server.ts"
export { assertEquals } from "https://deno.land/std@0.140.0/testing/asserts.ts"

// main.ts
import { serve, assertEquals } from "./deps.ts"

Advantages:

  • Unified version control.
  • Simplified import paths.

Principle of Least Privilege

# Grant only necessary permissions
deno run --allow-net=api.example.com --allow-read=./data main.ts

Security Recommendations:

  • Avoid using --allow-all.
  • Fine-tune permission scopes (e.g., specify allowed domains).

Leveraging the Caching Mechanism

# Manually pre-cache dependencies
deno cache --import-map=import_map.json main.ts

# View cache location
deno info

Cache Directory:

  • Defaults to ~/.deno/dir (customizable via DENO_DIR environment variable).

Standard Library Updates and Version Control

Version Specification:

// Use specific version
import { serve } from "https://deno.land/std@0.140.0/http/server.ts"

// Or manage uniformly via import map
{
  "imports": {
    "std/": "https://deno.land/std@0.140.0/"
  }
}

Upgrade Strategy:

By effectively combining these standard library modules, developers can rapidly build high-performance, secure Deno applications while maintaining code simplicity and maintainability.

Share your love