[Bun] Bun notes
Bun 课堂笔记
对比 | Node.js | Bun |
---|---|---|
语言 | C++ | Zig |
JS 引擎 | V8 | JSCore |
关于 V8 和 JSCore 各自有不同的架构和优化策略:
- JSC 优先考虑的是更快的启动时间和更少的内存占用,执行时间会稍微久一下
- V8 优先考虑快速执行,同时进行运行时的优化,但是 V8 会导致更多的内存占用
因此 Bun 这个运行时的特点就是速度很快,特别是启动速度,基本比 Node.js 快 3-4 倍。
Bun 官网:https://bun.sh/
首先第一步需要安装 Bun,直接使用 npm 全局安装即可:
npm install -g bun
安装完成之后通过 bun -v 可以查看版本。
包管理器
Bun 除了是一个 JavaScript 运行时,同时还是一个包管理器。
回顾在 Node.js 环境中,流行的包管理器:
- npm(官方)
- yarn
- pnpm
但是 Bun 中,天然就自带包管理器。
测试运行器
Bun 同时还自带测试运行器。Bun 的内部有一个内置的测试模块 bun:test
如果你熟悉 Jest/Vitest,那么你可以无缝的迁移过来,零学习成本。
总结
Bun 首先是一个 JS 的运行时,但是不仅仅是运行时,还是一个全能的工具包,其中包含了:
- 包管理器
- 测试运行器
- 构建工具
- 转译器(天生支持 ts)
除此之外,Bun 还有相当多的非常实用的特性:
- 天生支持 ts 以及 JSX
- ESM 和 CommonJS 兼容
- 内置 WebAPI
- 能够使用顶层 await
- 热更新
Elysia
Elysia 是一个基于 Bun 运行时的 Web 框架。
官网地址:https://elysiajs.com/
Performance
// node-server.js
import http from "http";
const hostname = "localhost";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World By Node.js");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/ by Node.js`);
});
// bun-server.js
// 在 Bun 这个运行时里面,内置了一个全局的对象叫做 Bun
// 这个对象里面有一些全局的方法,比如说 Bun.serve
// 该方法就是创建一个服务器
const server = Bun.serve({
port: 3001,
fetch() {
return new Response("Hello World!");
},
});
console.log(`Server is running at http://localhost:${server.port} by Bun`);
// test_node.js
import fetch from "node-fetch";
let count = 1000; // 要发送的请求数量,初始化为 1000
const start = Date.now(); // 开始时间
let err_count = 0; // 错误数量
async function runTest() {
while (count > 0) {
try {
const res = await fetch("http://localhost:3000");
await res.text();
count--;
} catch (err) {
err_count++;
}
}
const end = Date.now(); // 结束时间
console.log(`花费时间为:${end - start}ms`);
console.log(`错误数量为:${err_count}`);
}
runTest();
// test_bun.js
import fetch from "node-fetch";
let count = 1000; // 要发送的请求数量,初始化为 1000
const start = Date.now(); // 开始时间
let err_count = 0; // 错误数量
async function runTest() {
while (count > 0) {
try {
const res = await fetch("http://localhost:3001");
await res.text();
count--;
} catch (err) {
err_count++;
}
}
const end = Date.now(); // 结束时间
console.log(`花费时间为:${end - start}ms`);
console.log(`错误数量为:${err_count}`);
}
runTest();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-11-24 [AWS] Create a serverless API with Ampt and TypeScript
2022-11-24 [Typescript] 114. Hard - Camelize
2021-11-24 [RxJS] Execution Contexts and Scheduler
2020-11-24 [React] Broadcaster + Operator + Listener pattern -- 21. useBroadcaster & useListener Example 2 (allowWhen)
2015-11-24 [Javascript] Intro to Recursion
2014-11-24 [AnuglarJS] TweenMax with ngAnimate