Deno Cheatsheet

Deno Cheatsheet

May 14, 2020
Cheatsheets
★ Star me on GitHub

Deno 1.0 is just out! Let’s make a cheatsheet for it!

This cheatsheet will update continuously, any feedback is welcome.

Read Deno Manual for more details.


Installation

curl -fsSL https://deno.land/x/install/install.sh | sh

# or
brew install deno
# upgrade
deno upgrade

# check version
deno -V # deno 1.0.0
deno -help

Hello World:

// example.js
import { serve } from "https://deno.land/[email protected]/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}

Run Deno script:

deno fmt example.js # format source files
deno run example.js # execute a script

# start the REPL
deno
# evaluate code
deno eval "console.log(30933 + 404)" # 31337

Import third party modules(ES Modules):

import * as log from "https://deno.land/std/log/mod.ts";

Allow network access:

deno run --allow-net=example.com example.js
# or
deno run --allow-net example.js

Allow file access:

deno run --allow-read example.js
deno run --allow-write example.js

Command line argument

Deno.args.length
Deno.args[0]

Fetch URL:

const res = await fetch(url);
const body = new Uint8Array(await res.arrayBuffer());
await Deno.stdout.write(body);

Read files:

let file = await Deno.open(filename);
await Deno.copy(file, Deno.stdout);
file.close();

a echo TCP server:

const listener = Deno.listen({ port: 8080 });
console.log("listening on 0.0.0.0:8080");
for await (const conn of listener) {
  Deno.copy(conn, conn);
}

Execute wasm binaries:

const wasmModule = new WebAssembly.Module(wasmCode);
const wasmInstance = new WebAssembly.Instance(wasmModule);
wasmInstance.exports.main()

Install a module:

deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts
# export PATH="$HOME/.deno/bin:$PATH"
file_server .

file_server serves files in the current directory over HTTP. Just like python3 -m http.server


Multiple threads:

// worker.ts
console.log("hello world");
self.close();

// main.ts
new Worker("./worker.ts", { type: "module" });
deno run --allow-read main.ts # --allow-read permission is required

Writing tests

import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
Deno.test("hello world", () => {
  const x = 1 + 2;
  assertEquals(x, 3);
});

Test asynchronous code:

Deno.test("async hello world", async () => {
  const x = 1 + 2;
  // await some async task
  await delay(100);
  if (x !== 3) {
    throw Error("x should be equal to 3");
  }
});

Running tests:

deno test # Auto run test match {*_,}test.{js,ts,jsx,tsx} in the current directory (recursively)
# or
deno test my_test.ts