Deno 是 Node.js 之父新造的轮子. 旨在用 Golang 和 TypeScript 实现一个很小的 JS runtime.(其目标不是取代 Node.js)
由于 Deno 还没有发布可直接运行的二进制文件, 所以想要了解 Deno 的功能的话你有两种方式:
下载 Deno 源码自行编译
直接看源码
第一种方式我在 macOS 上折腾了好久, 依然出现各种报错, 只好作罢, 现在只能等 GitHub 网友推出 Dockerfile 再试试. 有在 macOS 上运行成功的可以说下经验.
第二种方式其实也不算难, 因为目前 Deno 的功能真的挺少的.
源码速读
首先打开 https://github.com/ry/deno/blob/master/deno.d.ts 可以看到 deno 提供的 API
- declare module "deno" {
- type MessageCallback = (msg: Uint8Array) => void;
- function sub(channel: string, cb: MessageCallback): void;
- function pub(channel: string, payload: Uint8Array): null | ArrayBuffer;
- function readFileSync(filename: string): Uint8Array;
- function writeFileSync(
- filename: string,
- data: Uint8Array,
- perm: number
- ): void;
- }
sub,pub,readFileSync 和 writeFileSync 共四个.
前两个 API 的使用方式见: https://github.com/ry/deno/blob/a4d89f2ee1ddde786f2335eada86f00e3efd1174/testdata/009_pub_sub.ts
后两个 API 的使用方式见: https://github.com/ry/deno/blob/eb259ee1546ebce9ce7a446b345899920f271b73/tests.ts
除此之外还有其他 API, 见 https://github.com/ry/deno/tree/master/testdata 里面的 15 个左右的测试文件, 目测有如下功能:
- console.log
- import { returnsHi, returnsFoo2, printHello3 } from"./subdir/mod1.ts";
- import { printHello } from"http://localhost:4545/testdata/subdir/print_hello.ts";
- setTimeout
- setInterval
- throwError
- https://github.com/ry/deno/blob/a4d89f2ee1ddde786f2335eada86f00e3efd1174/fetch.ts#L124
提供了 window 全局变量 https://github.com/ry/deno/blob/a4d89f2ee1ddde786f2335eada86f00e3efd1174/globals.ts#L14
提供了 TextEncoder https://github.com/ry/deno/blob/a4d89f2ee1ddde786f2335eada86f00e3efd1174/globals.ts#L55
提供了 os#exit,os#codeFetch 和 os#codeCache https://github.com/ry/deno/blob/master/os.ts#L8 (用途我还没看出来)
提供了一个极小的 runtime https://github.com/ry/deno/blob/master/runtime.ts , 按照官方说法, 这个 runtime 可移植性很好
其他
上面是 JS 方面的功能, 有些功能应该没写进测试里, 我还没时间细看.
可以看出 Deno 从一开始就没有想要兼容 Node.js.
除此之外 Deno 还有一个 V8 worker, 它提供的 API 也很简单:
- declare namespace V8Worker2 {
- function print(...args: any[]): void;
- type RecvCallback = (ab: ArrayBuffer) => void;
- function recv(cb: RecvCallback): void;
- function send(ab: ArrayBuffer): null | ArrayBuffer;
- }
就这三个 API.send 和 recv 的使用方法见 https://github.com/ry/deno/blob/a4d89f2ee1ddde786f2335eada86f00e3efd1174/dispatch.ts#L60 . deno#pub 就是基于 send 实现的.
如果你看好 Deno, 现在学习 go, 然后看 Deno 源码, 说不定一年后你就是 Deno 大佬了~!
就算 Deno 没火, 你也学会了 go, 转职 go 工程师指日可待, 真是百利而无一害~
少年, 我看好你.
来源: https://juejin.im/post/5b10d89d6fb9a01e31281a65