一、Deno 簡介
Deno 是一個 JavaScript/TypeScript 的運行時,默認使用安全環境執行代碼,有著卓越的開發體驗,Deno 含有以下功能亮點:
默認安全,外部代碼沒有檔案系統、網路、環境的訪問權限,除非顯式開啟,
支持開箱即用的 TypeScript 的環境,
只分發一個獨立的可執行檔案(deno),
有著內建的工具箱,比如一個依賴資訊查看器(deno info)和一個代碼格式化工具(deno fmt),
有一組經過審計的 標準模塊,保證能在 Deno 上作業,
腳本代碼能被打包為一個單獨的 JavaScript 檔案,
Deno 是一個跨平臺的運行時,即基于 Google V8 引擎的運行時環境,該運行時環境是使用 Rust 語言開發的,并使用 Tokio 庫來構建事件回圈系統,Deno 建立在 V8、Rust 和 Tokio 的基礎上,它的架構如下:
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 (denodeno/ops/dispatch_json.ts:43:11) at Object.sendSync (denodeno/ops/dispatch_json.ts:72:10) at Object.listen (denodeno/ops/net.ts:51:10) at Object.listen (denodeno/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,然后運行,
不知道看完本篇文章后,小伙伴們對 Deno 有沒有產生興趣呢?如果有的話,歡迎小伙伴給我留言,后續我再來一篇使用 Deno 開發 Web API 的文章哈,
五、參考資源
Deno 中文手冊
the-deno-handbook
deno-first-approach
在這里奉上一份學習線路圖

更多學習內容:請關注我的知乎專欄 高級前端工程師前端學習教程,從基礎到進階,看完保證讓你的薪資上升一個臺階,你也能成為阿里人(持續更新)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/85297.html
標籤:JavaScript
