Bun 内置模块全解析:告别第三方依赖,提升开发效率

作为新一代 JavaScript/TypeScript 运行时,Bun 最吸引人的特性之一就是内置了大量高频开发场景的核心模块 ------无需再安装 fs-extracross-envnode-fetch 等第三方依赖,一行代码就能搞定文件操作、终端命令、HTTP 请求、加密解密等常见需求。本文将系统拆解 Bun 的核心内置模块,结合实战示例讲透用法,帮你彻底用好 Bun 的原生能力。

一、为什么 Bun 内置模块值得关注?

在 Node.js 中,我们常常需要:

  • node-fetch 处理 HTTP 请求
  • fs-extra 增强文件操作
  • execa 执行终端命令
  • dotenv 管理环境变量
  • jest/vitest 做单元测试

而 Bun 把这些高频能力原生内置,带来两个核心优势:

  1. 🚄 更快:内置模块基于 Zig 编写,性能远超 Node.js 第三方库
  2. 📦 更轻:项目无需维护庞大的 node_modules,依赖体积骤减
  3. 🔄 更统一:API 设计贴近浏览器标准(如 fetch),学习成本更低

二、核心内置模块实战解析

2.1 🔥 Bun.shell:终端命令执行(替代 execa/cmd-shim)

Bun.shell 是 Bun 内置的终端命令执行工具,支持同步/异步、管道操作、跨平台,无需再装 execachild_process

核心特性

  • 异步/同步执行命令
  • 自动处理跨平台路径(Windows/macOS/Linux)
  • 支持管道、重定向
  • 内置错误处理

实战示例

javascript 复制代码
// 1. 异步执行单个命令(推荐)
const runCommand = async () => {
  // 执行 `ls -la` 命令(macOS/Linux),Windows 可换 `dir`
  const result = await Bun.$`ls -la`;
  
  // 命令执行结果解构
  console.log("退出码:", result.exitCode); // 0 表示成功
  console.log("标准输出:", result.stdout.toString());
  console.log("标准错误:", result.stderr.toString());
};

// 2. 同步执行命令(简单场景)
const syncResult = Bun.$`echo "Hello Bun"`.text();
console.log(syncResult); // 输出:Hello Bun

// 3. 管道操作(组合多个命令)
const pipeResult = await Bun.$`echo "Bun 内置模块" | grep "Bun"`.text();
console.log(pipeResult); // 输出:Bun 内置模块

// 4. 动态参数(安全拼接,避免注入)
const dirName = "src";
const dynamicResult = await Bun.$`ls -la ${dirName}`.text();
console.log(dynamicResult);

适用场景

  • 自动化脚本(如构建、部署)
  • 项目初始化/依赖安装
  • 跨平台命令执行

2.2 📁 Bun.file & Bun.write:文件操作(替代 fs/fs-extra)

Bun 提供了极简的文件操作 API,Bun.file() 替代 fs.readFileBun.write() 替代 fs.writeFile,支持流式操作、二进制处理,API 更简洁。

核心特性

  • 异步优先,性能远超 Node.js fs 模块
  • 支持文件读取、写入、追加、复制
  • 内置 JSON/YAML 解析
  • 支持大文件流式处理

实战示例

javascript 复制代码
// 1. 读取文件(自动处理编码)
const readFile = async () => {
  // 读取文本文件
  const textFile = Bun.file("./README.md");
  const content = await textFile.text(); // 读取为字符串
  console.log("文件内容:", content);

  // 读取 JSON 文件(自动解析)
  const jsonFile = Bun.file("./package.json");
  const pkg = await jsonFile.json(); // 直接解析为对象
  console.log("包名:", pkg.name);

  // 读取二进制文件
  const binFile = Bun.file("./logo.png");
  const buffer = await binFile.arrayBuffer();
  console.log("二进制长度:", buffer.byteLength);
};

// 2. 写入文件
const writeFile = async () => {
  // 写入文本
  await Bun.write("./test.txt", "Hello Bun!");

  // 写入 JSON(自动序列化)
  await Bun.write("./config.json", {
    name: "Bun App",
    port: 3000,
  });

  // 追加内容到文件
  await Bun.write("./log.txt", "新日志内容\n", { append: true });
};

// 3. 复制文件
const copyFile = async () => {
  await Bun.write("./dist/README.md", Bun.file("./README.md"));
};

适用场景

  • 配置文件读写
  • 日志记录
  • 静态资源处理
  • 大文件上传/下载

2.3 🌐 Bun.fetch:HTTP 请求(替代 node-fetch/axios)

Bun 内置了与浏览器完全兼容的 fetch API,无需安装任何 HTTP 库,支持请求/响应拦截、超时配置、FormData 等,性能比 axios 快 3 倍以上。

核心特性

  • 100% 兼容浏览器 fetch API
  • 支持 HTTP/1.1、HTTP/2、HTTPS
  • 内置超时、重试配置
  • 支持 Stream 流式响应

实战示例(对接你之前的菜单接口)

javascript 复制代码
// 封装 HTTP 请求函数
const request = async (url, options = {}) => {
  try {
    const response = await fetch(url, {
      method: options.method || "GET",
      headers: options.headers || {},
      body: options.body ? JSON.stringify(options.body) : undefined,
      timeout: options.timeout || 10000, // 超时 10 秒
    });

    if (!response.ok) {
      throw new Error(`HTTP 错误:${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("请求失败:", error.message);
    throw error;
  }
};

// 调用示例:新增菜单接口
const addMenu = async () => {
  const url = "https://qysys.tongyuan.cc:19443/api/userAuth/menu/v1.0/add";
  const result = await request(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer your-token-here",
    },
    body: {
      functionId: "123",
      name: "测试菜单",
    },
  });
  console.log("新增菜单结果:", result);
};

适用场景

  • 接口调用(RESTful API)
  • 爬虫/数据抓取
  • 文件上传/下载
  • 微服务通信

2.4 🔐 Bun.password:加密解密(替代 bcrypt/crypto)

Bun 内置了密码哈希、加密解密模块,无需安装 bcryptcrypto-js,支持常见的哈希算法(bcrypt、argon2)和加密算法(AES、SHA)。

核心特性

  • 支持 bcrypt/argon2 密码哈希
  • 内置 AES-256-GCM 加密
  • 无需编译原生模块(Node.js 的 bcrypt 需编译)

实战示例

javascript 复制代码
// 1. 密码哈希(推荐用于用户密码存储)
const hashPassword = async (password) => {
  // 使用 bcrypt 算法哈希密码
  const hash = await Bun.password.hash(password, {
    algorithm: "bcrypt", // 可选:argon2id、bcrypt
    cost: 10, // 复杂度(bcrypt 推荐 10-12)
  });
  return hash;
};

// 验证密码
const verifyPassword = async (password, hash) => {
  const isMatch = await Bun.password.verify(password, hash);
  return isMatch;
};

// 2. AES 加密/解密
const encryptData = async (data, secretKey) => {
  // 加密
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secretKey),
    { name: "AES-GCM" },
    false,
    ["encrypt", "decrypt"]
  );
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const encrypted = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv },
    key,
    encoder.encode(data)
  );
  return {
    iv: Buffer.from(iv).toString("base64"),
    data: Buffer.from(encrypted).toString("base64"),
  };
};

适用场景

  • 用户密码存储
  • 敏感数据加密
  • 接口签名/验签

2.5 🧪 Bun.test:内置测试框架(替代 Jest/Vitest)

Bun 内置了兼容 Jest API 的测试框架,无需配置,无需安装额外依赖,运行速度比 Jest 快 20 倍以上。

核心特性

  • 兼容 Jest 语法(describe、it、expect)
  • 内置代码覆盖率
  • 支持快照测试、模拟函数
  • 零配置启动

实战示例

javascript 复制代码
// test.js
import { test, expect, describe } from "bun:test";

// 测试普通函数
const sum = (a, b) => a + b;

describe("sum 函数测试", () => {
  test("1 + 2 应该等于 3", () => {
    expect(sum(1, 2)).toBe(3);
  });

  test("负数相加正确", () => {
    expect(sum(-1, -2)).toBe(-3);
  });
});

// 运行测试:bun test test.js

适用场景

  • 单元测试
  • 集成测试
  • E2E 测试(配合 Bun 内置的 fetch

2.6 📍 其他实用内置模块

模块 作用 替代的第三方库
Bun.env 环境变量处理 dotenv
Bun.build 代码构建/打包(TS/JS/JSX) webpack/rollup/esbuild
Bun.format 代码格式化(TS/JS) prettier
Bun.sql SQLite 数据库操作 sqlite3
Bun.ffi 调用 C 语言函数 node-ffi

三、Bun 内置模块 vs Node.js 第三方依赖

功能场景 Node.js 方案 Bun 方案 优势
HTTP 请求 axios/node-fetch Bun.fetch 无需安装,更快,更兼容
文件操作 fs/fs-extra Bun.file/Bun.write API 更简洁,性能更高
终端命令 execa/child_process Bun.shell 跨平台,管道支持更好
测试 Jest/Vitest Bun.test 零配置,速度快 20 倍
加密 bcrypt/crypto-js Bun.password/crypto 无需编译,原生支持

四、使用注意事项

  1. 兼容性 :Bun 目前仍在快速迭代,部分边缘 API 可能有小变动,生产环境建议锁定 Bun 版本(如 bun@1.0.25)。
  2. 迁移成本:从 Node.js 迁移时,大部分内置模块 API 可直接替换第三方库,仅需少量语法调整。
  3. 调试 :Bun 内置 bun debug 命令,支持 Chrome DevTools 调试,体验与 Node.js 一致。

五、总结 📝

Bun 的内置模块体系彻底重构了 JavaScript 开发的依赖生态,核心优势可总结为三点:

  1. 少依赖 :告别 node_modules 臃肿,内置模块覆盖 80% 高频开发场景;
  2. 高性能:基于 Zig 编写的内置模块,性能远超 Node.js 第三方库;
  3. 低学习成本:API 贴近浏览器标准,无需记忆多套库的用法。

如果你正在做 Node.js 迁移、脚本开发、小型服务端应用,Bun 的内置模块能让你少写代码、少装依赖、跑得更快------不妨从一个小脚本开始尝试,体验下一代运行时的便捷!

🌟 拓展阅读:Bun 官方文档(bun.sh/docs),可查看所有... API。

相关推荐
米丘1 小时前
vue-router v5.x 路由模式关于 createWebHistory、 createWebHashHistory的实现
前端
踩着两条虫1 小时前
AI 驱动的 Vue3 应用开发平台 深入探究(二):核心概念之DSL模式与数据模型
前端·vue.js·ai编程
进击的尘埃1 小时前
中介者模式:把面板之间的蜘蛛网拆干净
javascript
牛奶1 小时前
200 OK不是"成功"?HTTP状态码潜规则
前端·http·浏览器
Hilaku2 小时前
OpenClaw 很爆火,但没人敢聊它的权限安全🤷‍♂️
前端·javascript·程序员
ConardLi2 小时前
OpenClaw 完全指南:这可能是全网最新最全的系统化教程了!
前端·人工智能·后端
丁哥3 小时前
99.9%纯AI 做了一个ICO图标生成器(免费 全尺寸 不限文件大小)2ICO.CN欢迎品鉴
前端
兆子龙3 小时前
React Native 完全入门:从原理到实战
前端·javascript
哇哇哇哇3 小时前
vue3 watch解析
前端