Deno

Secure JavaScript/TypeScript runtime - built-in TypeScript, secure by default, modern standard library

TL;DR

What: Secure runtime for JavaScript and TypeScript by Node.js creator.

Why: Secure by default, native TypeScript, modern APIs, single executable, web standard APIs.

Quick Start

Install:

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

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

# Homebrew
brew install deno

Run scripts:

deno run hello.ts
deno run --allow-net server.ts
deno run https://deno.land/std/examples/welcome.ts

Cheatsheet

CommandDescription
deno run fileRun file
deno run --allow-netAllow network
deno run --allow-readAllow file read
deno testRun tests
deno fmtFormat code
deno lintLint code
deno compileCreate executable
deno task nameRun task

Gotchas

Permission flags

# Network access
deno run --allow-net server.ts
deno run --allow-net=api.example.com server.ts

# File access
deno run --allow-read file.ts
deno run --allow-write file.ts
deno run --allow-read=/tmp file.ts

# Environment variables
deno run --allow-env app.ts

# All permissions (not recommended)
deno run --allow-all app.ts

# Short form
deno run -A app.ts

HTTP server

// server.ts
Deno.serve({ port: 8000 }, (request: Request) => {
  const url = new URL(request.url);

  if (url.pathname === "/") {
    return new Response("Hello Deno!");
  }

  if (url.pathname === "/json") {
    return Response.json({ message: "Hello" });
  }

  return new Response("Not Found", { status: 404 });
});
deno run --allow-net server.ts

Importing modules

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

// From npm
import express from "npm:express@4";

// With import map (deno.json)
import { z } from "zod";
// deno.json
{
  "imports": {
    "zod": "npm:zod@3"
  }
}

Testing

// math_test.ts
import { assertEquals } from "https://deno.land/std/assert/mod.ts";

Deno.test("addition", () => {
  assertEquals(2 + 2, 4);
});

Deno.test("async test", async () => {
  const result = await Promise.resolve(42);
  assertEquals(result, 42);
});
deno test
deno test --watch

Configuration (deno.json)

{
  "tasks": {
    "dev": "deno run --allow-net --watch server.ts",
    "start": "deno run --allow-net server.ts",
    "test": "deno test --allow-read"
  },
  "imports": {
    "std/": "https://deno.land/[email protected]/",
    "oak": "https://deno.land/x/[email protected]/mod.ts"
  },
  "compilerOptions": {
    "strict": true
  }
}
deno task dev
deno task test

File I/O

// Read file
const text = await Deno.readTextFile("./data.txt");
const data = JSON.parse(await Deno.readTextFile("./data.json"));

// Write file
await Deno.writeTextFile("./output.txt", "Hello World");
await Deno.writeTextFile("./data.json", JSON.stringify({ key: "value" }));

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

Next Steps