跳转至

Deno 2.0 运行时

Deno 是 Node.js 创始人 Ryan Dahl 开发的新一代 JavaScript/TypeScript 运行时,默认安全(需要显式授权才能访问文件/网络),内置 TypeScript 支持和开发工具,兼容 npm 生态。

核心知识点

知识点说明
工具定位安全优先的 JS/TS/Wasm 运行时
最新版本Deno 2.6+(2025.12)
开发者Ryan Dahl(Node.js 创始人)
引擎V8 + Rust + Tokio
核心优势默认安全、原生 TypeScript、内置工具链
npm 兼容完全支持 npm 包和 node_modules
内置工具fmt、lint、test、bench、compile、audit

安装配置

# 安装 Deno
curl -fsSL https://deno.land/install.sh | sh  # 安装
deno --version                                  # 查看版本

# 或用 Homebrew
brew install deno

基本使用

1. 运行脚本

# 直接运行 TypeScript(无需配置)
deno run hello.ts                       # 运行本地文件
deno run https://example.com/script.ts  # 运行远程脚本

# 权限控制(Deno 的安全模型)
deno run --allow-read file.ts           # 允许读文件
deno run --allow-net server.ts          # 允许网络访问
deno run --allow-all script.ts          # 允许所有权限

2. Web 服务器

// server.ts
Deno.serve({ port: 3000 }, (req: Request) => {  // 内置 HTTP 服务器
  const url = new URL(req.url);
  if (url.pathname === "/api/hello") {
    return Response.json({ message: "Hello from Deno!" });
  }
  return new Response("Not Found", { status: 404 });
});
deno run --allow-net server.ts          # 运行时需要网络权限

3. 包管理

deno add npm:express                    # 添加 npm 包
deno add jsr:@std/fs                    # 添加 JSR 包
deno remove npm:express                 # 移除包

4. 内置工具

deno fmt                                # 格式化代码
deno lint                               # 代码检查
deno test                               # 运行测试
deno bench                              # 性能基准测试
deno compile server.ts                  # 编译为独立可执行文件
deno audit                              # 安全审计依赖

5. 测试

// test.ts
import { assertEquals } from "jsr:@std/assert";

Deno.test("加法测试", () => {
  assertEquals(1 + 2, 3);
});

Deno.test("异步测试", async () => {
  const data = await fetch("https://api.example.com/data");
  assertEquals(data.status, 200);
});

高级用法

编译为可执行文件

# 把 TypeScript 编译为独立的可执行文件(无需安装 Deno)
deno compile --allow-net --allow-read server.ts
# 生成的二进制文件可以直接在没有 Deno 的机器上运行

常见报错与解决

报错信息原因解决方法
PermissionDenied缺少权限添加对应 --allow-xxx 标志
Module not found导入路径错检查 URL 或包名
TypeError: fetch需要网络权限--allow-net

速查表

# ===== Deno 速查表 =====

# 安装
curl -fsSL https://deno.land/install.sh | sh

# 运行
deno run file.ts                # 运行
deno run --allow-all file.ts    # 全权限运行

# 权限标志
--allow-read     文件读取
--allow-write    文件写入
--allow-net      网络访问
--allow-env      环境变量
--allow-run      执行子进程
--allow-all      全部权限

# 工具
deno fmt          格式化
deno lint         代码检查
deno test         测试
deno bench        基准测试
deno compile      编译为可执行文件
deno audit        安全审计

# 包管理
deno add npm:pkg  添加 npm deno add jsr:pkg  添加 JSR