【Deno】597- 了不起的 Deno 入門教程

創建了一個 “重學TypeScript” 的微信羣,想加羣的小夥伴,加我微信 "semlinker",備註重學TS。

一、Deno 簡介

Deno 是一個 JavaScript/TypeScript 的運行時,默認使用安全環境執行代碼,有着卓越的開發體驗。Deno 含有以下功能亮點:

  • 默認安全。外部代碼沒有文件系統、網絡、環境的訪問權限,除非顯式開啓。

  • 支持開箱即用的 TypeScript 的環境。

  • 只分發一個獨立的可執行文件(deno)。

  • 有着內建的工具箱,比如一個依賴信息查看器(deno info)和一個代碼格式化工具(deno fmt)。

  • 有一組經過審計的 標準模塊,保證能在 Deno 上工作。

  • 腳本代碼能被打包爲一個單獨的 JavaScript 文件。

Deno 是一個跨平臺的運行時,即基於 Google V8 引擎的運行時環境,該運行時環境是使用 Rust 語言開發的,並使用  Tokio 庫來構建事件循環系統。Deno 建立在 V8、Rust 和 Tokio 的基礎上,它的架構如下:

(圖片來源:https://deno.land/manual/contributing/architecture)

1.1 Rust

Rust 是由 Mozilla 主導開發的通用、編譯型編程語言。設計準則爲 “安全、併發、實用”,支持函數式、併發式、過程式以及面向對象的編程風格。Deno 使用 Rust 語言來封裝 V8 引擎,通過 libdeno 綁定,我們就可以在 JavaScript 中調用隔離的功能。

1.2 Tokio

Tokio 是 Rust 編程語言的異步運行時,提供異步事件驅動平臺,構建快速,可靠和輕量級網絡應用。利用 Rust 的所有權和併發模型確保線程安全。Tokio 構建於 Rust 之上,提供極快的性能,使其成爲高性能服務器應用程序的理想選擇。在 Deno 中 Tokio 用於並行執行所有的異步 IO 任務。

1.3 V8

V8 是一個由 Google 開發的開源 JavaScript 引擎,用於 Google Chrome 及 Chromium 中。V8 在運行之前將JavaScript 編譯成了機器代碼,而非字節碼或是解釋執行它,以此提升性能。更進一步,使用瞭如內聯緩存(inline caching)等方法來提高性能。有了這些功能,JavaScript 程序與 V8 引擎的速度媲美二進制編譯。在 Deno 中,V8 引擎用於執行 JavaScript 代碼。

二、安裝 Deno

Deno 能夠在 macOS、Linux 和 Windows 上運行。Deno 是一個單獨的可執行文件,它沒有額外的依賴。你可以通過以下方式來安裝它:

  • 使用 Shell (macOS 和 Linux):

curl -fsSL https://deno.land/x/install/install.sh | sh
  • 使用 PowerShell (Windows):

iwr https://deno.land/x/install/install.ps1 -useb | iex
  • 使用 Scoop (Windows):

scoop install deno
  • 使用 Chocolatey (Windows):

choco install deno
  • 使用 Homebrew (macOS):

brew install deno
  • 使用 Cargo (Windows,macOS,Linux):

cargo install deno

Deno 也可以手動安裝,只需從 github.com/denoland/deno/releases 下載一個 zip 文件。它僅包含一個單獨的可執行文件。在 macOS 和 Linux 上,你需要爲它設置執行權限。當你成功安裝之後,可以通過執行 deno --version 命令來查看已安裝的 Deno 版本:

$ deno --version
deno 1.0.0
v8 8.4.300
typescript 3.9.2

2.1 deno-cli

deno-cli 命令行界面提供了一組集成功能,讓你可以沉浸在 Deno 的專有開發環境中。以下是 Deno 1.0.0 版本支持的所有子命令:

SUBCOMMANDS:
  bundle         Bundle module and dependencies into single file
  cache          Cache the dependencies
  completions    Generate shell completions
  doc            Show documentation for a module
  eval           Eval script
  fmt            Format source files
  help           Prints this message or the help of the given subcommand(s)
  info           Show info about cache or info related to source file
  install        Install script as an executable
  repl           Read Eval Print Loop
  run            Run a program given a filename or url to the module
  test           Run tests
  types          Print runtime TypeScript declarations
  upgrade        Upgrade deno executable to given version

2.2 REPL

在命令中輸入 deno 命令,你就會啓動一個 REPL(Read-Execute-Print-Loop):

$ deno
Deno 1.0.0
exit using ctrl+d or close()
> 1 + 2
3
> const name = "semlinker";
undefined
> console.log(name);
semlinker
undefined

三、Deno 初體驗

3.1 welcome demo

相信一些讀者安裝完 Deno 已經迫不及待了,現在我們立馬來體驗一下 Deno 應用程序。首先打開你熟悉的命令行,然後在命令行輸入以下命令:

$ deno run https://deno.land/std/examples/welcome.ts
Download https://deno.land/std/examples/welcome.ts
Warning Implicitly using master branch https://deno.land/std/examples/welcome.ts
Compile https://deno.land/std/examples/welcome.ts
Welcome to Deno ????

通過觀察以上輸出,我們可以知道當運行 deno run https://deno.land/std/examples/welcome.ts 命令之後,Deno 會先從 https://deno.land/std/examples/welcome.ts URL 地址下載 welcome.ts 文件,該文件的內容是:

console.log("Welcome to Deno ????");

當文件下載成功後,Deno 會對  welcome.ts 文件進行編譯,即編譯成 welcome.ts.js 文件,然後再通過 V8 引擎來執行編譯生成的 JavaScript 文件。需要注意的是,如果你在命令行重新運行上述命令,則會執行緩存中已生成的文件,並不會再次從網上下載 welcome.ts 文件。

$ deno run https://deno.land/std/examples/welcome.ts
Welcome to Deno ????

那如何證明再次執行上述命令時, Deno 會優先執行緩存中編譯生成的 JavaScript 文件呢?這裏我們要先介紹一下 deno info 命令,該命令用於顯示有關緩存或源文件相關的信息:

$ deno info
DENO_DIR location: "/Users/fer/Library/Caches/deno"
Remote modules cache: "/Users/fer/Library/Caches/deno/deps"
TypeScript compiler cache: "/Users/fer/Library/Caches/deno/gen"

在上述的輸出信息中,我們看到了 TypeScript compiler cache 這行記錄,很明顯這是 TypeScript 編譯器緩存的目錄,進入該目錄後,通過一層層的查找,我們最終在 examples 目錄下找到了 welcome.ts.js 文件:

➜  examples ls
welcome.ts.js     welcome.ts.js.map welcome.ts.meta

打開目錄中 welcome.ts.js 文件,我們可以看到以下內容:

"use strict";
console.log("Welcome to Deno ????");
//# sourceMappingURL=file:///Users/fer/Library/Caches/deno/gen/https/deno.land/std/examples/welcome.ts.js.map

下面我們來修改該文件,在文件中添加一行輸出信息 console.log("Hello Semlinker, from Cache");,具體如下:

"use strict";
console.log("Hello Semlinker, from Cache");
console.log("Welcome to Deno ????");
//# sourceMappingURL=file:///Users/fer/Library/Caches/deno/gen/https/deno.land/std/examples/welcome.ts.js.map

接着我們在命令行中重新執行以下命令:

$ deno run https://deno.land/std/examples/welcome.ts
Hello Semlinker, from Cache
Welcome to Deno ????

那麼現在問題又來了,如何強制刷新緩存,即重新編譯 TypeScript 代碼呢?針對這個問題,在運行 deno run 命令時,我們需要添加 --reload 標誌,來告訴 Deno 需要重新刷新指定文件:

$ deno run --reload https://deno.land/std/examples/welcome.ts
Download https://deno.land/std/examples/welcome.ts
Warning Implicitly using master branch https://deno.land/std/examples/welcome.ts
Compile https://deno.land/std/examples/welcome.ts
Welcome to Deno ????

除了 --reload 標誌之外,Deno run 命令還支持很多其他的標誌,感興趣的讀者可以運行 deno run --help 命令來查看更多的信息。

3.2 TCP echo server

前面我們已經介紹瞭如何運行官方的 welcome 示例,下面我們來介紹如何使用 Deno 創建一個簡單的 TCP echo 服務器。首先我們創建一個 learn-deno 項目,然後在該項目下新建一個 quickstart 目錄,接着新建一個 echo_server.ts 文件並輸入以下代碼:

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

for await...of 語句會在異步或者同步可迭代對象上創建一個迭代循環,包括 String,Array,Array-like 對象(比如 arguments 或者 NodeList),TypedArray,Map, Set 和自定義的異步或者同步可迭代對象。

for await...of 的語法如下:

for await (variable of iterable) {
  statement
}

輸入完以上代碼之後,相信很多讀者會跟我一樣,直接在命令行運行以下命令:

➜  quickstart deno run ./echo_server.ts 
Compile file:///Users/fer/LearnProjects/learn-deno/quickstart/echo_server.ts
error: Uncaught PermissionDenied: network access to "0.0.0.0:8080", run again with the --allow-net flag
    at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
    at Object.sendSync ($deno$/ops/dispatch_json.ts:72:10)
    at Object.listen ($deno$/ops/net.ts:51:10)
    at Object.listen ($deno$/net.ts:152:22)
    at file:///Users/fer/LearnProjects/learn-deno/quickstart/echo_server.ts:1:23

很明顯是權限錯誤,從錯誤信息中,Deno 告訴我們需要設置 --allow-net 標誌,以允許網絡訪問。爲什麼會這樣呢?這是因爲 Deno 是一個 JavaScript/TypeScript 的運行時,默認使用安全環境執行代碼。下面我們添加 --allow-net 標誌,然後再次運行 echo_server.ts 文件:

➜  quickstart deno run --allow-net ./echo_server.ts
listening on 0.0.0.0:8080

當服務器成功運行之後,我們使用 nc 命令來測試一下服務器的功能:

➜  ~ nc localhost 8080
hell semlinker
hell semlinker

介紹完如何使用 Deno 創建一個簡單的 TCP echo 服務器,我們再來介紹一下如何使用 Deno 創建一個簡單的 HTTP 服務器。

3.3 HTTP Server

與 TCP Server 一樣,在 quickstart 目錄下,我們新建一個 http_server.ts 文件並輸入以下內容:

import { serve } from "https://deno.land/[email protected]/http/server.ts";

const PORT = 8080;
const s = serve({ port: PORT });

console.log(` Listening on <http://localhost>:${PORT}/`);

for await (const req of s) {
  req.respond({ body: "Hello Semlinker\\n" });
}

友情提示:在實際開發過程中,你可以從 https://deno.land/std 地址獲取所需的標準庫版本。示例中我們顯式指定了版本,當然你也可以不指定版本,比如這樣:https://deno.land/std/http/server.ts 。

在上述代碼中,我們導入了 Deno 標準庫 http 模塊中 serve 函數,然後使用該函數快速創建 HTTP 服務器,該函數的定義如下:

// std/http/server.ts
export function serve(addr: string | HTTPOptions): Server {
  if (typeof addr === "string") {
    const [hostname, port] = addr.split(":");
    addr = { hostname, port: Number(port) };
  }

  const listener = listen(addr);
  return new Server(listener);
}

serve 函數接收一個參數,其類型是 string | HTTPOptions,其中 HTTPOptions 接口的定義如下:

/** Options for creating an HTTP server. */
export type HTTPOptions = Omit<Deno.ListenOptions, "transport">;

export interface ListenOptions {
    /** The port to listen on. */
    port: number;
    /** A literal IP address or host name that can be resolved to an IP address.
     * If not specified, defaults to `0.0.0.0`. */
    hostname?: string;
}

當輸入的參數類型是字符串時,serve 函數會使用 : 冒號對字符串進行切割,獲取 hostname 和 port,然後包裝成對象賦值給 addr 參數,接着使用 addr 參數繼續調用 listen 函數進一步創建 listener 對象,最終調用 new Server(listener) 創建 HTTP 服務器。

創建完 HTTP 服務器,我們來啓動該服務器,打開命令行輸入以下命令:

➜  quickstart deno run --allow-net ./http_server.ts 
Compile file:///Users/fer/LearnProjects/learn-deno/quickstart/http_server.ts
 Listening on <http://localhost>:8080/

接着打開瀏覽器,在地址欄上輸入 http://localhost:8080/ 地址,之後在當前頁面中會看到以下內容:

Hello World\n

四、調試 Deno

Deno 支持 V8 Inspector Protocol。使用 Chrome Devtools 或其他支持該協議的客戶端(比如 VSCode)能夠調試 Deno 程序。要啓用調試功能,用 --inspect--inspect-brk 選項運行 Deno,對應的選項描述如下:

--inspect=<HOST:PORT>
  activate inspector on host:port (default: 127.0.0.1:9229)

--inspect-brk=<HOST:PORT>
  activate inspector on host:port and break at start of user script

--inspect 選項允許在任何時間點連接調試器,而 --inspect-brk 選項會等待調試器連接,在第一行代碼處暫停執行。

4.1 Chrome Devtools

讓我們用 Chrome 開發者工具來調試一個簡單的程序,我們將使用來自 std 的 file_server.ts,這是一個簡單的靜態文件服務。

使用 --inspect-brk 選項,在第一行代碼處暫停執行。

$ deno run --inspect-brk --allow-read --allow-net https://deno.land/[email protected]/http/file_server.ts
Debugger listening on ws://127.0.0.1:9229/ws/1e82c406-85a9-44ab-86b6-7341583480b1
Download https://deno.land/[email protected]/http/file_server.ts
Compile https://deno.land/[email protected]/http/file_server.ts
...

打開 chrome://inspect,點擊 Target 旁邊的 Inspect

進一步瞭解更詳細的調試說明,可訪問https://deno.land/manual/tools/debugger URL 地址。

4.2 VSCode

Deno 可以在 VSCode 中調試。插件的官方支持正在開發中 https://github.com/denoland/vscode_deno/issues/12,當然我們也可以通過手動提供 launch.json 配置,來連接調試器:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Deno",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceFolder}",
      "runtimeExecutable": "deno",
      "runtimeArgs": ["run", "--inspect-brk", "-A", "<entry_point>"],
      "port": 9229
    }
  ]
}

注意:將 <entry_point> 替換爲實際的腳本名稱。

下面讓我們來嘗試一下調試本地源文件,創建 server.ts

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

<entry_point> 改爲 server.ts,然後運行。

(圖片來源:https://deno.land/manual/tools/debugger)

(圖片來源:https://deno.land/manual/tools/debugger)

不知道看完本篇文章後,小夥伴們對 Deno 有沒有產生興趣呢?如果有的話,歡迎小夥伴給我留言,後續我再來一篇使用 Deno 開發 Web API 的文章哈。

五、參考資源

  • Deno 中文手冊

  • the-deno-handbook

  • deno-first-approach

往期精彩回顧

 

一文讀懂 TS 中 Object, object, {} 類型之間的區別

一文讀懂 TS 中 Object, object, {} 類型之間的區別

 

掌握 TS 這些工具類型,讓你開發事半功倍

掌握 TS 這些工具類型,讓你開發事半功倍

 

遇到這些 TS 問題你會頭暈麼?

遇到這些 TS 問題你會頭暈麼?

聚焦全棧,專注分享 Angular、TypeScript、Node.js 、Spring 技術棧等全棧乾貨。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章