Hello World - 第一个程序 #
快速开始 #
最简单的方式 #
bash
# 直接执行代码
bun -e "console.log('Hello, Bun!')"
# 输出
# Hello, Bun!
创建文件 #
bash
# 创建项目目录
mkdir my-bun-app
cd my-bun-app
# 创建入口文件
echo "console.log('Hello, Bun!');" > index.js
# 运行
bun run index.js
# 输出
# Hello, Bun!
JavaScript 示例 #
基础示例 #
javascript
// index.js
console.log("Hello, Bun!");
// 变量声明
const name = "Bun";
const version = 1.2;
console.log(`Welcome to ${name} v${version}!`);
运行:
bash
bun run index.js
使用 ES 模块 #
javascript
// math.js
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
javascript
// index.js
import { add, multiply } from "./math.js";
console.log("1 + 2 =", add(1, 2));
console.log("3 * 4 =", multiply(3, 4));
使用 CommonJS #
javascript
// math.cjs
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = { add, multiply };
javascript
// index.cjs
const { add, multiply } = require("./math.cjs");
console.log("1 + 2 =", add(1, 2));
console.log("3 * 4 =", multiply(3, 4));
TypeScript 示例 #
基础 TypeScript #
typescript
// index.ts
interface User {
name: string;
age: number;
}
function greet(user: User): string {
return `Hello, ${user.name}! You are ${user.age} years old.`;
}
const user: User = {
name: "Bun",
age: 3,
};
console.log(greet(user));
运行:
bash
# 直接运行,无需编译
bun run index.ts
类型导入 #
typescript
// types.ts
export interface Product {
id: number;
name: string;
price: number;
}
export type Status = "pending" | "completed" | "cancelled";
typescript
// index.ts
import type { Product, Status } from "./types";
const product: Product = {
id: 1,
name: "Bun Book",
price: 29.99,
};
const status: Status = "completed";
console.log(product, status);
泛型示例 #
typescript
// utils.ts
export function identity<T>(arg: T): T {
return arg;
}
export function first<T>(arr: T[]): T | undefined {
return arr[0];
}
export function map<T, U>(arr: T[], fn: (item: T) => U): U[] {
return arr.map(fn);
}
typescript
// index.ts
import { identity, first, map } from "./utils";
console.log(identity<string>("Hello"));
console.log(first([1, 2, 3]));
console.log(map([1, 2, 3], (x) => x * 2));
JSX 示例 #
React 组件 #
tsx
// app.tsx
function Button({ children, onClick }: {
children: string;
onClick?: () => void
}) {
return (
<button
onClick={onClick}
style={{ padding: "10px 20px", fontSize: "16px" }}
>
{children}
</button>
);
}
function App() {
const handleClick = () => console.log("Button clicked!");
return (
<div>
<h1>Hello, Bun + React!</h1>
<Button onClick={handleClick}>Click Me</Button>
</div>
);
}
// 渲染为字符串
console.log(<App />);
运行:
bash
bun run app.tsx
配置 JSX #
创建 tsconfig.json:
json
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "react"
}
}
或使用其他 JSX 库:
json
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
HTTP 服务器示例 #
基础服务器 #
typescript
// server.ts
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("Hello, Bun!");
}
if (url.pathname === "/json") {
return Response.json({ message: "Hello, JSON!" });
}
return new Response("Not Found", { status: 404 });
},
});
console.log("Server running at http://localhost:3000");
运行:
bash
bun run server.ts
# 访问 http://localhost:3000
带路由的服务器 #
typescript
// router.ts
const routes: Record<string, () => Response> = {
"/": () => new Response("Home Page"),
"/about": () => new Response("About Page"),
"/api/status": () => Response.json({ status: "ok", time: Date.now() }),
};
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
const handler = routes[url.pathname];
if (handler) {
return handler();
}
return new Response("Not Found", { status: 404 });
},
});
console.log("Server running at http://localhost:3000");
热重载服务器 #
bash
# 使用 --hot 参数实现热重载
bun --hot run server.ts
typescript
// server.ts
Bun.serve({
port: 3000,
fetch(req) {
return new Response(`Server started at ${new Date().toISOString()}`);
},
});
console.log("Server running at http://localhost:3000");
文件操作示例 #
读取文件 #
typescript
// read.ts
// 方式一:使用 Bun.file()
const file = Bun.file("./data.txt");
const text = await file.text();
console.log(text);
// 方式二:使用 Bun.read()
const content = await Bun.read("./data.txt");
console.log(content);
// 方式三:读取 JSON
const data = await Bun.file("./data.json").json();
console.log(data);
写入文件 #
typescript
// write.ts
// 方式一:使用 Bun.write()
await Bun.write("./output.txt", "Hello, Bun!");
// 方式二:写入 JSON
await Bun.write("./output.json", JSON.stringify({ name: "Bun" }));
// 方式三:写入 Buffer
const buffer = new TextEncoder().encode("Hello, Buffer!");
await Bun.write("./buffer.txt", buffer);
文件监控 #
typescript
// watch.ts
const watcher = Bun.watch("./", {
recursive: true,
});
watcher.on("change", (event, filename) => {
console.log(`File changed: ${filename}`);
console.log(`Event: ${event}`);
});
console.log("Watching for changes...");
SQLite 示例 #
基础数据库操作 #
typescript
// database.ts
import { Database } from "bun:sqlite";
// 创建内存数据库
const db = new Database(":memory:");
// 创建表
db.run(`
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// 插入数据
db.run("INSERT INTO users (name, email) VALUES (?, ?)", ["Bun", "bun@example.com"]);
db.run("INSERT INTO users (name, email) VALUES (?, ?)", ["User", "user@example.com"]);
// 查询数据
const users = db.query("SELECT * FROM users").all();
console.log(users);
// 查询单条
const user = db.query("SELECT * FROM users WHERE id = ?").get(1);
console.log(user);
// 关闭数据库
db.close();
使用 ORM 风格 #
typescript
// orm.ts
import { Database } from "bun:sqlite";
const db = new Database(":memory:");
// 创建表
db.run(`
CREATE TABLE products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL
)
`);
// 预编译语句
const insertStmt = db.prepare("INSERT INTO products (name, price) VALUES ($name, $price)");
const selectStmt = db.prepare("SELECT * FROM products WHERE price > $minPrice");
// 批量插入
const insertMany = db.transaction((products) => {
for (const product of products) {
insertStmt.run(product);
}
});
insertMany([
{ $name: "Apple", $price: 1.5 },
{ $name: "Banana", $price: 2.0 },
{ $name: "Orange", $price: 1.8 },
]);
// 查询
const expensiveProducts = selectStmt.all({ $minPrice: 1.5 });
console.log(expensiveProducts);
db.close();
网络请求示例 #
fetch API #
typescript
// fetch.ts
// GET 请求
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const post = await response.json();
console.log(post);
// POST 请求
const createResponse = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Bun Post",
body: "Hello from Bun!",
userId: 1,
}),
});
const newPost = await createResponse.json();
console.log(newPost);
WebSocket #
typescript
// websocket.ts
const ws = new WebSocket("wss://echo.websocket.org");
ws.onopen = () => {
console.log("Connected!");
ws.send("Hello, WebSocket!");
};
ws.onmessage = (event) => {
console.log("Received:", event.data);
};
ws.onerror = (error) => {
console.error("Error:", error);
};
ws.onclose = () => {
console.log("Disconnected");
};
package.json 配置 #
创建项目 #
bash
# 初始化项目
bun init
# 或手动创建
touch package.json
package.json 示例 #
json
{
"name": "my-bun-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "bun run index.ts",
"dev": "bun --hot run index.ts",
"test": "bun test",
"build": "bun build ./src/index.ts --outdir ./dist"
},
"dependencies": {},
"devDependencies": {
"bun-types": "latest"
}
}
运行脚本 #
bash
# 运行 start 脚本
bun start
# 运行 dev 脚本
bun dev
# 运行测试
bun test
项目结构示例 #
推荐结构 #
text
my-bun-app/
├── src/
│ ├── index.ts # 入口文件
│ ├── routes/
│ │ └── api.ts
│ ├── utils/
│ │ └── helpers.ts
│ └── types/
│ └── index.ts
├── tests/
│ └── index.test.ts
├── public/
│ └── index.html
├── package.json
├── tsconfig.json
└── bunfig.toml
入口文件 #
typescript
// src/index.ts
import { serveAPI } from "./routes/api";
import { logger } from "./utils/helpers";
const PORT = process.env.PORT || 3000;
Bun.serve({
port: PORT,
fetch: serveAPI,
});
logger(`Server running at http://localhost:${PORT}`);
下一步 #
恭喜你完成了第一个 Bun 程序!接下来学习 CLI 命令详解 深入了解 Bun 的命令行工具。
最后更新:2026-03-29