强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Deno 入门教程 / 第 03 章:Hello World

第 03 章:Hello World

3.1 你的第一个 Deno 程序

JavaScript 版本

创建文件 hello.js

// hello.js
console.log("Hello, Deno!");

运行:

deno run hello.js
# 输出:Hello, Deno!

TypeScript 版本

创建文件 hello.ts

// hello.ts
const message: string = "Hello, Deno!";
console.log(message);

运行:

deno run hello.ts
# 输出:Hello, Deno!

💡 注意:不需要 tsc 编译、不需要 ts-node、不需要 tsconfig.json——Deno 直接运行 .ts 文件。

直接执行代码

# 使用 -e 标志直接执行代码
deno run -e 'console.log("Hello, Deno!")'

# TypeScript 也行
deno run -e 'const x: number = 42; console.log(x)'

从 URL 运行

# 直接运行远程脚本
deno run https://deno.land/std@0.224.0/examples/cat.ts /etc/hosts

# 从 stdin 运行
echo 'console.log("Hello!")' | deno run -

3.2 deno run 命令详解

deno run 是最常用的命令,其完整语法:

deno run [OPTIONS] [SCRIPT] [SCRIPT_ARGS...]

常用选项

选项说明示例
--allow-read授予文件读取权限deno run --allow-read script.ts
--allow-write授予文件写入权限deno run --allow-write script.ts
--allow-net授予网络访问权限deno run --allow-net script.ts
--allow-env授予环境变量访问权限deno run --allow-env script.ts
--allow-all授予所有权限(谨慎!)deno run -A script.ts
--watch文件变化时自动重启deno run --watch script.ts
--inspect启用调试器deno run --inspect script.ts
--reload重新加载远程模块deno run --reload script.ts
--check执行类型检查deno run --check script.ts
--no-check跳过类型检查deno run --no-check script.ts
--unstable启用不稳定 APIdeno run --unstable script.ts

实用组合

# 运行时自动重启 + 网络权限(开发 Web 服务器常用)
deno run --watch --allow-net server.ts

# 运行并检查类型
deno run --check script.ts

# 运行并调试
deno run --inspect-brk script.ts
# 然后在 Chrome 打开 chrome://inspect 调试

3.3 TypeScript 原生支持

Deno 对 TypeScript 的支持是一等公民级别的。

零配置运行

// type-demo.ts
interface User {
  name: string;
  age: number;
  email?: string;  // 可选属性
}

function createUser(name: string, age: number): User {
  return { name, age };
}

const user: User = createUser("Alice", 30);
console.log(`用户:${user.name},年龄:${user.age}`);

// 类型错误会被捕获
// const badUser: User = createUser("Bob");  // Error: 缺少参数 age

运行:

deno run type-demo.ts
# 输出:用户:Alice,年龄:30

类型推断

Deno 完整支持 TypeScript 的类型推断:

// TypeScript 会自动推断类型
const numbers = [1, 2, 3];          // 推断为 number[]
const result = numbers.map(n => n * 2);  // 推断为 number[]

// 复杂类型推断
async function fetchData() {
  const res = await fetch("https://api.example.com");
  return res.json();  // 推断为 Promise<any>
}

泛型(Generics)

// generic-demo.ts
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const num = first([1, 2, 3]);        // T 推断为 number
const str = first(["a", "b", "c"]);  // T 推断为 string

console.log(num);  // 1
console.log(str);  // a

装饰器(Decorators)

// decorator-demo.ts
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`调用 ${propertyKey},参数:`, args);
    return original.apply(this, args);
  };
}

class Calculator {
  @Log
  add(a: number, b: number): number {
    return a + b;
  }
}

const calc = new Calculator();
calc.add(1, 2);
// 输出:调用 add,参数:[1, 2]

⚠️ 注意:装饰器需要在 deno.json 中配置 "compilerOptions": { "experimentalDecorators": true }


3.4 权限模型初探

Deno 默认是安全沙箱环境,任何需要系统资源的操作都需要显式授权。

权限错误演示

// permission-demo.ts
// 这段代码需要文件读取权限
try {
  const content = await Deno.readTextFile("hello.txt");
  console.log(content);
} catch (error) {
  console.error("读取文件失败:", error.message);
}
# 不授权运行
deno run permission-demo.ts
# 错误:PermissionDenied: Requires read access to "hello.txt"

# 授权后运行
deno run --allow-read permission-demo.ts

权限标志一览

标志简写说明
--allow-read[=path]-r文件读取权限
--allow-write[=path]-w文件写入权限
--allow-net[=host]-n网络访问权限
--allow-env[=var]-e环境变量访问权限
--allow-run[=cmd]子进程运行权限
--allow-ffi外部函数接口权限
--allow-sys[=api]系统信息访问权限
--allow-all-A所有权限(危险!)

精细权限控制

# 只允许读取特定目录
deno run --allow-read=/tmp,/etc script.ts

# 只允许访问特定域名
deno run --allow-net=api.example.com,cdn.example.com script.ts

# 只允许访问特定环境变量
deno run --allow-env=DB_HOST,DB_PORT script.ts

权限模型的详细介绍将在 第 05 章 中展开。


3.5 编译为可执行文件

Deno 可以将脚本编译为独立的可执行文件,无需安装 Deno 即可运行。

基本编译

// app.ts
console.log("这是一个编译后的 Deno 应用");
console.log("运行参数:", Deno.args);

const name = Deno.args[0] || "World";
console.log(`Hello, ${name}!`);
# 编译
deno compile app.ts

# 运行(无需 Deno)
./app Deno
# 输出:
# 这是一个编译后的 Deno 应用
# 运行参数: ["Deno"]
# Hello, Deno!

交叉编译

# 编译为 Windows 可执行文件
deno compile --target x86_64-pc-windows-msvc app.ts

# 编译为 macOS ARM64
deno compile --target aarch64-apple-darwin app.ts

# 编译为 Linux x86_64
deno compile --target x86_64-unknown-linux-gnu app.ts

支持的目标平台:

目标平台target 参数
Linux x86_64x86_64-unknown-linux-gnu
Linux ARM64aarch64-unknown-linux-gnu
macOS x86_64x86_64-apple-darwin
macOS ARM64aarch64-apple-darwin
Windows x86_64x86_64-pc-windows-msvc

带权限的编译

# 编译时嵌入权限标志
deno compile --allow-net --allow-read --output my-server server.ts

编译产物大小优化

# 默认编译约 80-100MB(包含 V8 引擎)
deno compile app.ts

# 使用 --lite 标志减小体积(需要运行时在线下载 V8)
deno compile --lite app.ts

3.6 deno 其他常用命令

deno eval

# 快速执行代码片段
deno eval 'console.log(1 + 2)'

# TypeScript 也支持
deno eval 'const x: number = 42; console.log(x)'

# 异步代码
deno eval 'const r = await fetch("https://example.com"); console.log(r.status)'

deno bench

# 运行性能基准测试
deno bench bench_test.ts

deno doc

# 查看模块文档
deno doc https://deno.land/std@0.224.0/http/server.ts

# 生成文档网站
deno doc --html mod.ts

deno jupyter

# 启动 Jupyter 笔记本(Deno 内核)
deno jupyter

3.7 开发工作流

一个典型的 Deno 项目开发流程:

# 1. 创建项目目录
mkdir my-deno-app && cd my-deno-app

# 2. 初始化配置
deno init

# 3. 创建主程序
cat > main.ts << 'EOF'
import { serve } from "https://deno.land/std@0.224.0/http/server.ts";

serve((req: Request) => {
  return new Response("Hello, Deno!");
}, { port: 8000 });

console.log("服务器运行在 http://localhost:8000");
EOF

# 4. 开发模式运行(自动重启)
deno run --watch --allow-net main.ts

# 5. 运行测试
deno test

# 6. 代码格式化
deno fmt

# 7. 代码检查
deno lint

# 8. 编译发布
deno compile --allow-net main.ts

deno init 命令

# 创建基本项目结构
deno init my-project
# 输出:
# Created my-project/deno.json
# Created my-project/main.ts
# Created my-project/main_test.ts

生成的 deno.json

{
  "tasks": {
    "dev": "deno run --watch main.ts",
    "test": "deno test"
  }
}

3.8 本章小结

要点说明
运行脚本deno run script.ts 直接运行 JS/TS
TypeScript零配置原生支持,包含类型检查
权限模型默认无权限,需 --allow-* 授权
编译deno compile 生成独立可执行文件
开发模式--watch 自动重启,--inspect 调试
快速执行deno eval 执行代码片段

📖 扩展阅读


下一章第 04 章:TypeScript 深入 → 深入了解 Deno 的 TypeScript 支持。