跳到主要内容

bun

警告
  • bun 目前还不适用于通用的生产环境
    • 相对来说,bun 更适用于前端项目而不是后端项目,因为 后端 项目通常需要更多的 node 兼容模块
  • musl 支持
  • deploy bun#211
  • 无 dns 模块 - 0.5+ - pg 不支持 #288
  • 无 async_hooks - sequelize 不支持
  • 未实现 dns, http2, https, child_process, vm, tls, async_hooks, worker_threads, inspector
  • 未实现 HTTP request body streaming
  • 未实现 HTTP2 不支持 gRPC
  • 兼容
    • 支持 vitest #4145
    • 支持 ReactNative #123
    • fetch 100 continue 问题 #7428
      • S3 SDK, fetch 请求
    • 支持 NestJS #1641
提示
  • bun 嵌入了 tinycc,有 jit 能力,因此 ffi 效率非常高
  • bun 还处于非常早期开发阶段
  • 使用 JavaScriptCore - 各有优缺点
  • bun 一些点的性能很好,但整体应用性能比不上 node
# Manually Install
# =======================
curl -LO https://ghproxy.com/https://github.com/oven-sh/bun/releases/download/bun-v1.0.29/bun-darwin-x64.zip
unzip bun-darwin-x64.zip
mv bun-darwin-x64/bun ~/bin/
xattr -r -d com.apple.quarantine ~/bin/bun
bun -v

bun upgrade # 升级
bun upgrade --canary # 升级到尚未发布版本 - bun 开发很快,可以提前尝试一些特性

docker run --rm -it wener/bun bun -v
docker run --rm --init --ulimit memlock=-1:-1 oven/bun # 官方镜像
docker run -it --rm -v $PWD:/host -w /host -p 3000:3000 --entrypoint bash oven/bun:debian
bun bun src/index.js
# https://github.com/oven-sh/bun/issues/211
./node_modules.bun > ./node_modules.js
npm add -D @types/bun

ffi

  • 目前应该无法将 number 转换为 Pointer
// 注意转换为 CString 需要 \0 结尾
function ptrOfStr(s?: string) {
return typeof s === 'string' ? ptr(Buffer.from(s + '\0', 'utf8')) : null;
}
import { viewSource } from 'bun:ffi';

// 生成的 C 代码
console.log(
viewSource(
{
hello_world: {
returns: 'float',
args: ['float'],
},
},
false,
)[0],
);
import { dlopen, FFIType } from 'bun:ffi';

// /lib/x86_64-linux-gnu/libc.so.6
// /usr/lib/x86_64-linux-gnu/libc.so.6
const { printf } = dlopen('libc.so.6', {
printf: { args: [FFIType.cstring, FFIType.f64] },
}).symbols;

printf(new TextEncoder().encode('%.17f\n'), 4);

memory

Bun.gc(true); // synchronous
Bun.gc(false); // asynchronous

macro

  • 类似 inline+预执行
import { random } from './random.ts' with { type: 'macro' };

compile

# 90MB+
bun build --compile ./src/main.ts --outfile myapp --external={pg-query-stream,better-sqlite3,tedious,oracledb,mysql2,sqlite3,mysql} --external=@mikro-orm/{migrations,entity-generator,better-sqlite,sqlite,mariadb,mysql,mongodb,seeder}

FAQ

hono

Failed to find Response internal state key

Failed to open library. This is usually caused by a missing library or an invalid library path.

检查下是不是 arch 错了。