Deno 速查表

Deno 速查表

May 14, 2020
速查表
★ 在 GitHub 赞我

Deno 刚出了 1.0! 我们为它制作了一个速查表(Cheatsheet)。

这份表会持续更新,欢迎反馈.

阅读官方文档了解更多。


安装

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

# 或者
brew install deno
# 升级
deno upgrade

# 检查版本
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" });
}

运行 Deno 脚本:

deno fmt example.js # 格式化源代码文件
deno run example.js # 执行脚本

# 运行 REPL
deno
# 执行代码
deno eval "console.log(30933 + 404)" # 31337

引入第三方模块(ES Modules):

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

允许网络访问:

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

允许文件访问:

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

命令行参数

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);

读取文件:

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

一个 echo TCP 服务器:

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);
}

执行 wasm 二进制文件:

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

安装模块:

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


多线程:

// 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

写测试用例

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

测试异步代码:

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");
  }
});

运行测试:

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