Deno

Essential Deno commands, APIs, and patterns for modern TypeScript/JavaScript runtime.

cli
denotypescriptjavascriptruntimebackend

Installation

# macOS/Linux
curl -fsSL https://deno.land/install.sh | sh

# Homebrew
brew install deno

# Windows (PowerShell)
irm https://deno.land/install.ps1 | iex

Deno vs npm Commands

TaskDenonpm
Initialize projectdeno initnpm init
Install dependenciesdeno installnpm install
Add a packagedeno add npm:lodashnpm install lodash
Add a dev dependencydeno add --dev npm:vitestnpm install -D vitest
Run a scriptdeno task devnpm run dev
Run testsdeno testnpm test
Format codedeno fmtnpm run prettier
Lint codedeno lintnpm run eslint
Execute a packagedeno run npm:cowsaynpx cowsay
Publish a packagedeno publishnpm publish

Updating Deno

# Update to latest version
deno upgrade

# Update to specific version
deno upgrade --version 2.0.0

# Check current version
deno --version

Version Management (DVM)

# Install DVM (macOS/Linux)
curl -fsSL https://dvm.deno.dev | sh

# Install a specific Deno version
dvm install 2.0.0

# List installed versions
dvm list

# List available versions
dvm list --all

# Switch to a specific version
dvm use 2.0.0

# Set default version
dvm alias default 2.0.0

# Uninstall a version
dvm uninstall 1.45.0

Running Scripts

# Run a TypeScript/JavaScript file
deno run script.ts

# Run with permissions
deno run --allow-net --allow-read script.ts

# Run with all permissions
deno run -A script.ts

# Run remote script
deno run https://deno.land/std/examples/welcome.ts

# Watch mode
deno run --watch script.ts

Permissions

# Network access
--allow-net
--allow-net=api.example.com

# File system read
--allow-read
--allow-read=/path/to/dir

# File system write
--allow-write
--allow-write=/path/to/dir

# Environment variables
--allow-env
--allow-env=API_KEY,SECRET

# Run subprocesses
--allow-run
--allow-run=git,npm

# FFI (Foreign Function Interface)
--allow-ffi

# All permissions
-A or --allow-all

Package Management

# Add a package (deno.json)
deno add @std/fs

# Install dependencies
deno install

# Cache dependencies
deno cache deps.ts

# Update dependencies
deno cache --reload deps.ts

Built-in Tools

# Format code
deno fmt

# Lint code
deno lint

# Type check
deno check script.ts

# Run tests
deno test

# Generate documentation
deno doc script.ts

# Bundle into single file
deno bundle script.ts output.js

# Compile to executable
deno compile script.ts

# Start REPL
deno repl

Importing Modules

// Import from URL
import { serve } from "https://deno.land/std/http/server.ts";

// Import from npm
import express from "npm:express";

// Import from deno.land/x
import { oakCors } from "https://deno.land/x/cors/mod.ts";

// Import from JSR (recommended)
import { parseArgs } from "jsr:@std/cli";

// Import map (deno.json)
import { fs } from "@std/fs";

HTTP Server

// Using Deno.serve (recommended)
Deno.serve({ port: 8000 }, (req) => {
  return new Response("Hello, World!");
});

// With routing
Deno.serve({ port: 8000 }, (req) => {
  const url = new URL(req.url);
  
  if (url.pathname === "/api") {
    return Response.json({ message: "Hello" });
  }
  
  return new Response("Not Found", { status: 404 });
});

File System

// Read file
const text = await Deno.readTextFile("file.txt");
const bytes = await Deno.readFile("file.bin");

// Write file
await Deno.writeTextFile("file.txt", "Hello");
await Deno.writeFile("file.bin", new Uint8Array([1, 2, 3]));

// Check if file exists
try {
  await Deno.stat("file.txt");
  console.log("File exists");
} catch {
  console.log("File does not exist");
}

// List directory
for await (const entry of Deno.readDir("./")) {
  console.log(entry.name, entry.isFile);
}

// Remove file/directory
await Deno.remove("file.txt");
await Deno.remove("dir", { recursive: true });

Environment Variables

// Get environment variable
const apiKey = Deno.env.get("API_KEY");

// Set environment variable
Deno.env.set("MY_VAR", "value");

// Get all environment variables
const allEnv = Deno.env.toObject();

Testing

// Basic test
Deno.test("example test", () => {
  const result = 1 + 1;
  if (result !== 2) throw new Error("Math is broken");
});

// Async test
Deno.test("async test", async () => {
  const response = await fetch("https://api.example.com");
  if (!response.ok) throw new Error("Request failed");
});

// Using assertions
import { assertEquals, assertThrows } from "jsr:@std/assert";

Deno.test("with assertions", () => {
  assertEquals(1 + 1, 2);
  assertThrows(() => {
    throw new Error("test");
  });
});

deno.json Configuration

{
  "tasks": {
    "dev": "deno run --watch --allow-all main.ts",
    "start": "deno run --allow-all main.ts",
    "test": "deno test --allow-all"
  },
  "imports": {
    "@std/": "jsr:@std/"
  },
  "compilerOptions": {
    "strict": true
  },
  "fmt": {
    "indentWidth": 2,
    "singleQuote": true
  },
  "lint": {
    "rules": {
      "exclude": ["no-unused-vars"]
    }
  }
}

Tasks

# Run a task defined in deno.json
deno task dev
deno task start
deno task test

# List available tasks
deno task

Fetch API

// GET request
const response = await fetch("https://api.example.com/data");
const data = await response.json();

// POST request
const response = await fetch("https://api.example.com/data", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Deno" }),
});

Web APIs

// URL API
const url = new URL("https://example.com/path?query=1");
console.log(url.pathname, url.searchParams.get("query"));

// TextEncoder/TextDecoder
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const bytes = encoder.encode("Hello");
const text = decoder.decode(bytes);

// crypto
const uuid = crypto.randomUUID();
const hash = await crypto.subtle.digest(
  "SHA-256",
  new TextEncoder().encode("message")
);