Lesson 28-Deno CLI Analysis

Deno’s command-line interface (CLI) is the core entry point for interaction, offering rich functionality and flexible configuration options. This article provides a comprehensive analysis of the Deno CLI, from basic commands to advanced usage, covering its working principles and practical techniques.

Deno CLI Core Architecture

CLI Command Structure

Deno CLI adopts a hierarchical command structure, categorized into three types:

  1. Core Commands: Provided directly by the Deno binary
    • run: Executes scripts
    • bundle: Bundles modules
    • fmt: Formats code
    • test: Runs tests
    • lint: Performs code linting
  2. Subcommands: Extensions of core commands
    • run --watch: File watching mode
    • test --coverage: Coverage reporting
  3. Global Flags: Universal options across commands
    • --allow-net: Network permissions
    • --import-map: Import map file

Detailed Execution Process:

  1. Argument Parsing: Uses the clap library to parse command-line arguments
  2. Permission Verification: Checks --allow-* permission flags
  3. Configuration Loading: Reads deno.json and import_map.json
  4. Functionality Execution: Invokes corresponding Rust implementation
  5. Result Output: Formats output to the console

Deep Dive into Core Commands

deno run Command

Basic Usage:

deno run [OPTIONS] <SCRIPT_ARG>...

Advanced Parameters Example:

# Run with permission control and cache optimization
deno run \
  --allow-read=./data \
  --allow-net=api.example.com \
  --reload=https://deno.land/x/oak \
  --v8-flags=--turbofan \
  --import-map=import_map.json \
  src/main.ts arg1 arg2

Parameter Details Table:

ParameterPurposeExample
--allow-readFile read permission--allow-read=./config
--allow-writeFile write permission--allow-write=./logs
--allow-netNetwork access permission--allow-net=api.example.com
--reloadForce cache refresh--reload=https://deno.land/x/*
--v8-flagsV8 engine options--v8-flags=--harmony
--import-mapImport map file--import-map=import_map.json
--watchFile watching mode--watch=src/**/*.ts

deno bundle Command

Module Bundling Principle:

  1. Resolves dependency graph of the entry file
  2. Applies import map for path resolution
  3. Merges all dependencies into a single file
  4. Generates optimized ES module or IIFE format

Advanced Bundling Example:

# Generate browser-compatible UMD bundle
deno bundle \
  --import-map=import_map.json \
  --no-check \
  src/main.ts \
  dist/bundle.js

# Generate type declaration file
deno bundle --config tsconfig.json src/main.ts dist/bundle.d.ts

Format Selection Guide:

FormatUse CaseFeatures
ES ModuleModern browsers/Node.jsSupports dynamic imports
IIFELegacy browsersImmediately Invoked Function Expression
UMDUniversal modulesCompatible with multiple environments

deno test Command

Test Execution Process:

  1. Discovers test files (*_test.ts)
  2. Loads test modules
  3. Executes test cases
  4. Generates test reports

Advanced Testing Features:

# Parallel testing with coverage
deno test \
  --allow-read=./testdata \
  --parallel \
  --coverage=./coverage \
  --filter="UserTest" \
  tests/

# Generate multi-format reports
deno coverage ./coverage \
  --lcov \
  --output=lcov.info

genhtml lcov.info -o coverage_report

Test Filtering Options:

OptionPurposeExample
--filterRegex match test names--filter="Login.*"
--shuffleRandomize execution order--shuffle
--fail-fastStop on first failure--fail-fast

Global Flags Explained

Permission Control Flags

Permission Matrix:

PermissionFlagSub-Permissions
File System--allow-read
--allow-write
Specific paths
Network--allow-netSpecific domains
Environment Variables--allow-envSpecific variable names
Subprocess Execution--allow-runRestricted commands
Plugins--allow-pluginRarely used

Path Restriction Example:

# Precise path control
deno run \
  --allow-read=/etc/config.json \
  --allow-write=./logs/app.log \
  app.ts

# Wildcard usage
deno run --allow-read=./data/*.json app.ts

Development Tool Flags

Common Development Flags:

FlagPurposeExample
--watchFile watching--watch=src/**/*.ts
--inspectDebug mode--inspect=9229
--no-checkSkip type checking--no-check
--locationSimulate URL--location=http://localhost

File Watching Mode:

# Watch multiple directories
deno run --watch=src/,tests/

# Customize watch interval
DENO_WATCH_POLL_INTERVAL_MS=1000 deno run --watch=src/

Configuration File System

deno.json Configuration

Complete Configuration Example:

{
  "tasks": {
    "dev": "deno run --allow-net --watch src dev_server.ts",
    "build": "deno compile --allow-net --import-map=import_map.json src/main.ts --output dist/main",
    "test": "deno test --coverage=cov_profile"
  },
  "imports": {
    "react": "https://esm.sh/react@18.3.1",
    "lodash": "https://esm.sh/lodash@4.17.21"
  },
  "compilerOptions": {
    "lib": ["dom", "esnext"],
    "target": "es2022"
  },
  "lint": {
    "rules": {
      "tags": ["recommended"],
      "include": ["src/**/*.ts"]
    }
  },
  "fmt": {
    "files": {
      "include": ["src/**/*.ts"],
      "exclude": ["src/**/*.test.ts"]
    }
  }
}

Configuration Items Explained:

ItemPurposeExample
tasksDefine common commands"dev": "deno run..."
importsSpecify import map file"react": "https://esm.sh/..."
compilerOptionsTypeScript compilation options"target": "es2022"
lintESLint configuration"rules": {...}
fmtPrettier configuration"files": {...}

import_map.json Management

Version Control Strategy:

{
  "imports": {
    "react": "https://esm.sh/react@18.3.1",
    "lodash": "https://esm.sh/lodash@4.17.21"
  },
  "scopes": {
    "https://esm.sh/": {
      "@types/react": "https://esm.sh/@types/react@18.3.3"
    }
  }
}

Updating Dependency Versions:

# Manually update version
sed -i 's/react@18.3.1/react@18.3.2/g' import_map.json

# Use tool to auto-update
deno run --allow-read=import_map.json update_deps.ts

Advanced Usage Techniques

Custom Subcommands

Shell-Based Encapsulation:

#!/bin/bash
# deno-mycommand

case $1 in
  "start")
    deno run --allow-net server.ts
    ;;
  "build")
    deno compile --allow-net src/main.ts --output dist/main
    ;;
  *)
    echo "Usage: deno-mycommand [start|build]"
    exit 1
    ;;
esac

Register as Global Command:

chmod +x deno-mycommand
sudo ln -s $(pwd)/deno-mycommand /usr/local/bin/deno-mycommand

Performance Optimization Techniques

Cache Control Strategies:

# Disable cache in development
deno run --no-remote dev_server.ts

# Force cache in production
deno run --cached-only main.ts

# Clear cache directory
deno cache --reload --no-remote

V8 Engine Tuning:

# Enable TurboFan optimization
deno run --v8-flags=--turbofan app.ts

# Adjust heap memory limit
deno run --v8-flags=--max-old-space-size=4096 app.ts

Debugging and Diagnostics

Debug Mode Usage:

# Start debug server
deno run --inspect=9229 app.ts

# Connect via Chrome DevTools
# chrome://inspect -> Configure -> Add port 9229

Performance Analysis Tools:

# Generate CPU profile
deno run --v8-flags=--cpu-prof app.ts

# Generate heap snapshot
deno run --v8-flags=--heap-prof app.ts

# Analyze with Chrome DevTools
# Open chrome://inspect -> Profiler

Common Issue Solutions

Permission Issue Troubleshooting

Error Example:

error: Uncaught PermissionDenied: read access to "/etc/passwd", run again with the --allow-read flag

Solutions:

  1. Specify exact path: deno run --allow-read=/etc/passwd app.ts
  2. Use environment variable to restrict scope: DENO_READ_PATHS="/etc/passwd" deno run app.ts

Dependency Cache Issues

Symptoms:

  • Code not updated after dependency changes
  • Inconsistent behavior across environments

Solutions:

# Force refresh all caches
deno cache --reload app.ts

# Clear specific dependency cache
deno cache --reload=https://deno.land/x/oak app.ts

# Delete global cache directory
rm -rf ~/.cache/deno

Cross-Platform Path Issues

Solution:

// Use Deno.path module for path handling
import { join } from "https://deno.land/std@0.224.0/path/mod.ts";

const configPath = join(Deno.cwd(), "config", "settings.json");

Windows-Specific Handling:

# Run Deno in WSL2
wsl deno run --allow-read=/mnt/c/Users/app.ts

# Or configure Git Bash path conversion
export MSYS_NO_PATHCONV=1
deno run app.ts
Share your love