How to Cache Modules in Deno: Simple Guide
In Deno, you can cache modules by running
deno cache <file> which downloads and stores dependencies locally. To use cached modules without re-downloading, run with --cached-only. To force re-download and update cache, use --reload.Syntax
The main commands to manage module caching in Deno are:
deno cache <file>: Downloads and caches all dependencies of the specified file.deno run --cached-only <file>: Runs the file using only cached modules, failing if modules are missing.deno run --reload <file>: Forces Deno to re-download all modules and update the cache.
bash
deno cache <file> deno run --cached-only <file> deno run --reload <file>
Example
This example shows how to cache modules for a script, run it using cached modules only, and then reload modules to update the cache.
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; console.log("Starting server on http://localhost:8000"); serve(() => new Response("Hello from Deno!"), { port: 8000 });
Output
Starting server on http://localhost:8000
Common Pitfalls
1. Running without cache: If you run deno run without prior caching, Deno downloads modules each time which slows startup.
2. Using --cached-only without cache: This causes an error if modules are not cached yet.
3. Forgetting to reload: If a remote module updates but you don't use --reload, your program uses stale code.
bash
/* Wrong: Running with --cached-only before caching modules */ deno run --cached-only server.ts /* Right: Cache modules first, then run with cached-only */ deno cache server.ts deno run --cached-only server.ts
Quick Reference
| Command | Purpose |
|---|---|
| deno cache | Download and cache dependencies without running |
| deno run --cached-only | Run using only cached modules, error if missing |
| deno run --reload | Force re-download and update cache |
| deno info | Show cached modules and their locations |
Key Takeaways
Use
deno cache to download and store modules locally before running.Run with
--cached-only to ensure no network requests and use only cached modules.Use
--reload to refresh cached modules when remote code changes.Running with
--cached-only without prior caching causes errors.Check cached modules and their paths with
deno info.