Bunとは
BunはZigで書かれた高速なJavaScriptランタイムです。Node.jsの3倍以上の速度を誇り、パッケージマネージャー、バンドラー、テストランナーを内蔵しています。
インストール
# macOS / Linux
curl -fsSL https://bun.sh/install | bash
# Windows (WSL推奨)
powershell -c "irm bun.sh/install.ps1 | iex"
# バージョン確認
bun --version
基本的な使い方
プロジェクト初期化
# 新規プロジェクト作成
bun init
# 対話形式でセットアップ
# package.json, tsconfig.json, index.ts が生成される
スクリプト実行
# TypeScriptを直接実行(トランスパイル不要)
bun run index.ts
# package.jsonのスクリプト実行
bun run dev
bun run build
# 省略形
bun dev
パッケージ管理
# パッケージインストール
bun add express
bun add -d typescript @types/node
# 全依存関係のインストール
bun install
# パッケージ削除
bun remove express
# アップデート
bun update
速度比較
# 同じpackage.jsonをインストール
# npm install: 15秒
# bun install: 1秒
HTTPサーバー
Bun組み込みサーバー
// server.ts
const server = Bun.serve({
port: 3000,
fetch(request) {
const url = new URL(request.url);
if (url.pathname === '/') {
return new Response('Hello, Bun!');
}
if (url.pathname === '/api/users') {
return Response.json([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
]);
}
return new Response('Not Found', { status: 404 });
},
});
console.log(`Server running at http://localhost:${server.port}`);
Honoフレームワーク
// Honoは Bun に最適化されたフレームワーク
import { Hono } from 'hono';
const app = new Hono();
app.get('/', (c) => c.text('Hello, Hono!'));
app.get('/api/users/:id', (c) => {
const id = c.req.param('id');
return c.json({ id, name: 'User' });
});
app.post('/api/users', async (c) => {
const body = await c.req.json();
return c.json({ created: body }, 201);
});
export default app;
ファイル操作
// ファイル読み込み
const file = Bun.file('data.json');
const content = await file.text();
const json = await file.json();
// ファイル書き込み
await Bun.write('output.txt', 'Hello, World!');
await Bun.write('data.json', JSON.stringify({ key: 'value' }));
// ストリーミング読み込み
const stream = file.stream();
for await (const chunk of stream) {
console.log(chunk);
}
環境変数
// .envファイルは自動的に読み込まれる
// .env
// DATABASE_URL=postgresql://localhost/mydb
// API_KEY=secret123
// 使用
const dbUrl = Bun.env.DATABASE_URL;
const apiKey = Bun.env.API_KEY;
// process.envも使用可能
const nodeEnv = process.env.NODE_ENV;
テスト実行
// sum.test.ts
import { expect, test, describe } from 'bun:test';
import { sum } from './sum';
describe('sum', () => {
test('adds two numbers', () => {
expect(sum(1, 2)).toBe(3);
});
test('handles negative numbers', () => {
expect(sum(-1, 1)).toBe(0);
});
});
# テスト実行
bun test
# 特定ファイル
bun test sum.test.ts
# ウォッチモード
bun test --watch
バンドル
# シングルファイルにバンドル
bun build ./index.ts --outdir ./dist
# ミニファイ
bun build ./index.ts --outdir ./dist --minify
# ターゲット指定
bun build ./index.ts --target bun
bun build ./index.ts --target browser
bun build ./index.ts --target node
Node.jsからの移行
互換性
// ほとんどのNode.js APIが使用可能
import fs from 'fs';
import path from 'path';
import { createServer } from 'http';
// node_modulesもそのまま使用可能
import express from 'express';
package.json
{
"name": "my-app",
"scripts": {
"dev": "bun run --watch src/index.ts",
"build": "bun build src/index.ts --outdir dist",
"test": "bun test",
"start": "bun run dist/index.js"
}
}
注意点
// 一部のNode.js固有APIは非対応
// - node:vm(一部)
// - node:worker_threads(Bun.workerを使用)
// Bun固有API
const hash = Bun.hash('data'); // 高速ハッシュ
const result = Bun.spawn(['ls', '-la']); // プロセス実行
SQLiteサポート
import { Database } from 'bun:sqlite';
const db = new Database('mydb.sqlite');
// テーブル作成
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// 挿入
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
insert.run('Alice', 'alice@example.com');
// クエリ
const query = db.prepare('SELECT * FROM users WHERE id = ?');
const user = query.get(1);
console.log(user);
関連記事
- Deno入門 - 別のモダンランタイム
- Honoフレームワーク - Bun最適化フレームワーク
- Node.js Express - 従来の選択肢
まとめ
Bunは高速なJavaScriptランタイムで、Node.jsの代替として注目されています。パッケージ管理、バンドル、テストが統合されており、開発体験が向上します。
← Back to list