温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com
点击访问原文链接

Bun — A fast all-in-one JavaScript runtime

Bun — A fast all-in-one JavaScript runtimeBun is joining Anthropic & Anthropic is betting on Bun →BuildDocsReferenceGuidesBlogDiscordBun v1.3.10New native REPL, --compile --target=browser for self-contained HTML, TC39 standard ES decorators, Windows ARM64 support, barrel import optimizat...Bun v1.3.9Run multiple scripts in --parallel or --sequential. bun:test mock & spyOn get Symbol.dispose support. ESM bytecode compilation. Faster Bun.markd...Bun v1.3.8Bun.markdown is a builtin CommonMark-compliant Markdown parser written in Zig. Bun's bundler gets bun build --metafile-md to write LLM-friendly ...Bun v1.3.750% faster `Buffer.from(array)`, 35% faster async/await, 3x faster `array.flat()`, 90% faster `padStart`/`padEnd` via JSC upgrade. New: `Bun.JSO...Bun v1.3.6Bun.Archive API for creating & extracting tarballs with gzip compression, Bun.JSONC for parsing JSON with comments, metafile & files options in ...Bun v1.3.5Bun.Terminal API, compile-time feature flags, improved Bun.stringWidth accuracy, V8 C++ value type checking APIs, Content-Disposition support fo...BuildDocsReferenceGuidesBlogDiscordBun v1.3.10 is here! →Bun is a fast JavaScript
all-in-one toolkit|

Bun is a fast, incrementally adoptable all-in-one JavaScript, TypeScript & JSX toolkit. Use individual tools like bun test or bun install in Node.js projects, or adopt the complete stack with a fast JavaScript runtime, bundler, test runner, and package manager built in. Bun aims for 100% Node.js compatibility.

Install Bun v1.3.10

Linux & macOSWindowsView install scriptcurl -fsSL https://bun.sh/install | bashpowershell -c "irm bun.sh/install.ps1 | iex"

USED BY

BundlerExpressPostgresWebSocketsBundling 10,000 React components

Build time in milliseconds (Linux x64, Hetzner)

Bunv1.3.0269.1 msRolldownv1.0.0-beta.42494.9 msesbuildv0.25.10571.9 msFarmv1.0.51,608 msRspackv1.5.82,137 msView benchmark →Express.js 'hello world'

HTTP requests per second (Linux x64)

bun: 59,026 requests per second59,026deno: 25,335 requests per second25,335node: 19,039 requests per second19,039Bunv1.2Denov2.1.6Node.jsv23.6.0View benchmark →WebSocket chat server

Messages sent per second (Linux x64, 32 clients)

bun: 2,536,227 messages sent per second2,536,227deno: 1,320,525 messages sent per second1,320,525node: 435,099 messages sent per second435,099Bun.serve()v1.2Deno.serve()v1.2.6ws (Node.js)v23.6.0View benchmark →Load a huge table

Queries per second. 100 rows x 100 parallel queries

bun: 28,571 queries per second28,571node: 14,522 queries per second14,522deno: 11,169 queries per second11,169Bunv1.2.22Node.jsv24.8.0Denov2.5.1View benchmark →Four tools, one toolkit

Use them together as an all-in-one toolkit, or adopt them incrementally. bun test works in Node.js projects. bun install can be used as the fastest npm client. Each tool stands on its own.

JavaScript RuntimeStarts 3x faster than Node.jsA fast JavaScript runtime designed as a drop-in replacement for Node.js$ bun ./index.tsNode.js API compatibilityTypeScript, JSX & React (zero config)Comprehensive builtin standard libraryPostgreSQL, Redis, MySQL, SQLiteHot & watch mode built-inEnvironment variables with .envREPLACESNode.jsPackage Manager30x fasterInstall packages up to 30x faster than npm with a global cache and workspaces$ bun installSimple migration from npm/pnpm/yarnEliminate phantom dependenciesWorkspaces, monoreposLifecycle scripts & postinstall handlingDependency auditing with bun auditBlock malicious packagesReplacesNPMTest RunnerReplaces Jest & VitestJest-compatible test runner with built-in code coverage and watch mode$ bun testJest-compatible expect() APISnapshot testingWatch mode & lifecycle hooksDOM APIs via happy-dom✓Concurrent test execution✓Built-in code coverageReplacesVitestBundlerReplaces Vite and esbuildBundle TypeScript, JSX, React & CSS for both browsers and servers$ bun build ./app.tsxTypeScript & JSX built-in (no config)CSS imports & bundling✓React support out of the box✓Build for the browser, Bun, and Node.jsSingle-file executables.html, .css, .ts, .tsx, .jsx & moreReplacesViteWho uses Bun?Claude Code uses Bun

Bun's single file executables & fast start times are great for CLIs.

Learn about single file executablesRailway Functions powered by Bun

Bun's all-in-one toolkit makes Railway's serverless functions fast and easy to use.

Deploy on RailwayMidjourney uses Bun

Bun's built-in WebSocket server helps Midjourney publish image generation notifications at scale.

Learn about Bun's WebSocket serverWhat's different about Bun?

Bun provides extensive builtin APIs and tooling

Builtin Core FeaturesBunNodeDenoNode.js compatibilityAiming to be a drop-in replacement for Node.js appsWeb Standard APIsSupport for web standard APIs like fetch, URL, EventTarget, Headers, etc.Powered by WebCore (from WebKit/Safari)Native AddonsCall C-compatible native code from JavaScriptBun.ffi, NAPI, partial V8 C++ APITypeScriptFirst-class support, including "paths" enum namespaceJSXFirst-class support without configurationModule loader pluginsPlugin API for importing/requiring custom file types`Bun.plugin` works in browsers & Bun3 different loader APIs. Server-side onlyBuiltin APIsBunNodeDenoPostgreSQL, MySQL, and SQLite driversConnect to any SQL database with one fast, unified APIFastest available, with query pipeliningS3 Cloud Storage driverUpload and download from S3-compatible storage, built-inFastest availableRedis clientRedis client built into Bun with Pub/Sub supportWebSocket server (including pub/sub)WebSocket server built into Bun.serve() with backpressure handling`Bun.serve()`HTTP serverLightning-fast HTTP server built into BunBun.serve()HTTP routerRoute HTTP requests with dynamic paths and wildcards, built into Bun.serve()Bun.serve({routes: {'/api/:path': (req) => { ... }}}})Single-file executablesCompile your app to a standalone executable that runs anywherebun build --compile with cross-compilation & code signingNo native addons, embedded files, cross-compilation or bytecode. Multi-step process.No native addons, no cross-compilationYAMLYAML is a first-class citizen in Bun, just like JSONBun.YAML & import from .yaml filesCookies APIParse and set cookies with zero overhead using a Map-like APIrequest.cookies Map-like APIEncrypted Secrets StorageStore secrets securely using your OS's native keychainBun.secrets (Keychain/libsecret/Windows Credential Manager)Builtin ToolingBunNodeDenonpm package managementInstall, manage, and publish npm-compatible dependenciesWith catalogs, isolated installs, bun audit, bun whyLimited featuresBundlerBuild production-ready code for frontend & backendBun.buildCross-platform $ shell APINative bash-like shell for cross-platform shell scripting`Bun.$`Requires 'dax'Jest-compatible test runnerTesting library compatible with the most popular testing frameworkbun test with VS Code integration & concurrent executionHot reloading (server)Reload your backend without disconnecting connections, preserving statebun --hotMonorepo supportInstall workspaces packages and run commands across workspacesbun run --filter=package-glob ...Frontend Development ServerRun modern frontend apps with a fully-featured dev serverbun ./index.htmlFormatter & LinterBuilt-in formatter and linterBuiltin UtilitiesBunNodeDenoPassword & Hashing APIsbcrypt, argon2, and non-cryptographic hash functions`Bun.password` & `Bun.hash`String Width APICalculate the width of a string as displayed in the terminalBun.stringWidthGlob APIGlob patterns for file matchingBun.Globfs.promises.globSemver APICompare and sort semver stringsBun.semverCSS color conversion APIConvert between CSS color formatsBun.colorCSRF APIGenerate and verify CSRF tokensBun.CSRFEverything you need to build & ship

Production-ready APIs and tools, built into Bun

HTTP & WebSocketsBun.serve()HTTP & WebSocket serverroutesBuilt-in routing with dynamic pathsrequest.cookiesZero-overhead cookie parsingDatabasesBun.sqlPostgreSQL, MySQL, SQLiteBun.s3S3-compatible cloud storageBun.redisRedis client with Pub/SubFile SystemBun.file()Fast file reading & streamingBun.GlobFast file pattern matchingBun.write()Write files efficientlyTestingbun testJest-compatible test runnersnapshotsSnapshot testing built-inexpect()Jest-compatible assertionsBuild & Deploybun buildFast bundler with tree-shaking--compileSingle-file executables--hotHot reload without restartsTypeScript & DXTypeScript & JSXNo config requiredimport "*.yaml"YAML & TOML importsimport "*.css"CSS & asset importsSecurityBun.passwordbcrypt, argon2 hashingBun.CSRFCSRF token generationBun.secretsOS keychain integrationSystem IntegrationBun.$Cross-platform shell scriptingBun.spawn()Spawn child processesbun:ffiCall native C/C++ librariesUtilitiesBun.hash()Fast hashing utilitiesBun.semverVersion comparisonBun.escapeHTML()HTML escaping & sanitization$ bun runBun is a JavaScript runtime.Bun is a new JavaScript runtime built from scratch to serve the modern JavaScript ecosystem. It has three major design goals:

Speed. Bun starts fast and runs fast. It extends JavaScriptCore, the performance-minded JS engine built for Safari. Fast start times mean fast apps and fast APIs.Elegant APIs. Bun provides a minimal set of highly-optimized APIs for performing common tasks, like starting an HTTP server and writing files.Cohesive DX. Bun is a complete toolkit for building JavaScript apps, including a package manager, test runner, and bundler.Bun is designed as a drop-in replacement for Node.js. It natively implements thousands of Node.js and Web APIs, including fs, path, Buffer and more.

The goal of Bun is to run most of the world's server-side JavaScript and provide tools to improve performance, reduce complexity, and multiply developer productivity.

Bun works with Next.jsLee Robinson

VP of Developer Experience at Cursor (Anysphere)

app/blog/[slug]/page.tsx

import { s3, $, sql } from "bun"; export default async function BlogPage({ params }) {  const [post] = await sql`    SELECT title, image_key, content    FROM posts    WHERE slug = ${params.slug}  `;   const imgUrl = s3.file(post.image_key).presign({•••expiresIn: 3600 });   const wordCount = await $`echo ${post.content} | wc -w`;   return (    div>      h1>{post.title}h1>      img src={imgUrl} />      p>Word count: {wordCount}p>    div>  );}Full speed full-stack

Fast frontend apps with Bun's built-in high performance development server and production bundler. You've never seen hot-reloading this fast!

Develop and ship frontend apps

Bun's built-in bundler and dev server make frontend development fast and simple. Develop with instant hot reload, then ship optimized production builds—all with zero configuration.

$ bun init --reactStart a dev server

Run bun ./index.html to start a dev server. TypeScript, JSX, React, and CSS imports work out of the box.

Hot Module Replacement

Built-in HMR preserves application state during development. Changes appear instantly—no manual refresh needed.

Build for production

Build optimized bundles with bun build ./index.html --production. Tree-shaking, minification, and code splitting work out of the box.

Learn more about frontend with Bun →$ bun installBun is an npm-compatible package manager.

Bun

pnpm

17x slower

npm

29x slower

Yarn

33x slower

Installing dependencies from cache for a Remix app.
View benchmark

Replace yarn with bun install to get 30x faster package installs.

Try it$ bun testBun is a test runner that makes the rest look like test walkers.

Bun

Vitest

5x slower

Jest+SWC

8x slower

Jest+tsjest

18x slower

Jest+Babel

20x slower

Replace jest with bun test to run your tests 10-30x faster.

Try itThe APIs you need. Baked in.

Start an HTTP server

Start a WebSocket server

Read and write files

Hash a password

Frontend dev server

Write a test

Query PostgreSQL

Use Redis

Import YAML

Set cookies

Run a shell script

Call a C function

index.tsximport { sql, serve } from "bun"; const server = serve({ port: 3000, routes: { "/": new Response("Welcome to Bun!"), "/api/users": async (req) => { const users = await sql`SELECT * FROM users LIMIT 10`; return Response.json({ users }); }, }, }); console.log(`Listening on localhost:${server.port}`);index.tsxconst server = Bun.serve: string; }>({ fetch(req, server) { // use a library to parse cookies const cookies = parseCookies(req.headers.get("Cookie")); server.upgrade(req, { data: { authToken: cookies['X-Token'] }, }); }, websocket: { // handler called when a message is received async message(ws, message) { console.log(`Received: ${message}`); const user = getUserFromToken(ws.data.authToken); await db.Message.insert({ message: String(message), userId: user.id, }); }, }, }); console.log(`Listening on localhost:${server.port}`);index.tsxconst file = Bun.file(import.meta.dir + '/package.json'); // BunFile const pkg = await file.json(); // BunFile extends Blob pkg.name = 'my-package'; pkg.version = '1.0.0'; await Bun.write(file, JSON.stringify(pkg, null, 2)); index.tsxconst password = "super-secure-pa$$word"; const hash = await Bun.password.hash(password); // => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh... const isMatch = await Bun.password.verify(password, hash); // => trueserver.ts// Run 'bun init --react' to get started import { serve } from "bun"; import reactApp from "./index.html"; serve({ port: 3000, routes: { "/": reactApp, "/api/hello": () => Response.json({ message: "Hello!" }), }, development: { console: true, // Stream browser logs to terminal hmr: true, // Enable hot module reloading }, });index.test.tsximport { test, expect } from "bun:test"; // Run tests concurrently for better performance test.concurrent("fetch user 1", async () => { const res = await fetch("https://api.example.com/users/1"); expect(res.status).toBe(200); }); test.concurrent("fetch user 2", async () => { const res = await fetch("https://api.example.com/users/2"); expect(res.status).toBe(200); }); test("addition", () => { expect(2 + 2).toBe(4); }); index.tsximport { sql } from "bun"; // Query with automatic SQL injection prevention const users = await sql` SELECT * FROM users WHERE active = ${true} LIMIT 10 `; // Insert with object notation const [user] = await sql` INSERT INTO users ${sql({ name: "Alice", email: "alice@example.com" })} RETURNING * `;config.yaml// Import YAML files directly import config from "./config.yaml"; console.log(config.database.host); // => "localhost" // Or parse YAML at runtime const data = Bun.YAML.parse(` name: my-app version: 1.0.0 database: host: localhost port: 5432 `);index.tsximport { serve } from "bun"; serve({ port: 3000, routes: { "/": (request) => { // Read cookies with built-in parsing const sessionId = request.cookies.get("session_id"); // Set cookies request.cookies.set("session_id", "abc123", { path: "/", httpOnly: true, secure: true, }); return Response.json({ success: true }); }, }, });index.tsximport { redis } from "bun"; // Set a key await redis.set("greeting", "Hello from Bun!"); console.log(db.query("SELECT 1 as x").get()); // { x: 1 } index.tsximport { $ } from 'bun'; // Run a shell command (also works on Windows!) await $`echo "Hello, world!"`; const response = await fetch("https://example.com"); // Pipe the response body to gzip const data = await $`gzip ${response}`.arrayBuffer();index.tsximport { dlopen, FFIType, suffix } from "bun:ffi"; // `suffix` is either "dylib", "so", or "dll" depending on the platform const path = `libsqlite3.${suffix}`; const { symbols: { sqlite3_libversion, // the function to call }, } = dlopen(path, { sqlite3_libversion: { args: [], // no arguments returns: FFIType.cstring, // returns a string }, }); console.log(`SQLite 3 version: ${sqlite3_libversion()}`);Learn moreDocumentationGet started with Bun and learn how to use all of its featuresAPI ReferenceExplore the complete API reference for Bun's runtime and toolkitDevelopers love Bun.SainderJan 17@Sainder_PradiptBunLicJan 18@Lik228bunMartin NavrátilJan 17@martin_nav_Bun....SaltyAomJan 17@saltyAombunreaxiosJan 17@reaxiosbun install bunkygeJan 17@0xkygebunJames LandrumJan 17@JamesRLandrumNodeorlowdevJan 17@orlowdevYeah, bun, but my code does not have dependencies.holaJan 17@jdggggyujhbcbunstd::venomJan 17@std_venomBuntiagoJan 19@tiagorangel23should have used Bun instead of npmSainderJan 17@Sainder_PradiptBunLicJan 18@Lik228bunMartin NavrátilJan 17@martin_nav_Bun....SaltyAomJan 17@saltyAombunreaxiosJan 17@reaxiosbun install bunkygeJan 17@0xkygebunJames LandrumJan 17@JamesRLandrumNodeorlowdevJan 17@orlowdevYeah, bun, but my code does not have dependencies.holaJan 17@jdggggyujhbcbunstd::venomJan 17@std_venomBuntiagoJan 19@tiagorangel23should have used Bun instead of npm46officialsJan 19@46officialsBunyukiJan 19@staticdotsBunStefanJan 17@stefangarofaloBunSamuelJan 17@samueldans0Bun alwaysDivin PrinceJan 17@divinprncYeah BunGibsonJan 16@GibsonSMurraybunOggie SutrisnaJan 16@oggiesutrisnabunemanonJan 16@0x_emanon✅ bunyukiJan 16@staticdotsbunSpiritBearJan 16@0xSpiritBearbunAyuJan 12@Ayuu2809Bun good 🧅46officialsJan 19@46officialsBunyukiJan 19@staticdotsBunStefanJan 17@stefangarofaloBunSamuelJan 17@samueldans0Bun alwaysDivin PrinceJan 17@divinprncYeah BunGibsonJan 16@GibsonSMurraybunOggie SutrisnaJan 16@oggiesutrisnabunemanonJan 16@0x_emanon✅ bunyukiJan 16@staticdotsbunSpiritBearJan 16@0xSpiritBearbunAyuJan 12@Ayuu2809Bun good 🧅HirbodJan 19@hirbod_devFor everything. Yes. I even run with bunx expo run:ios etcLuis PaoliniJan 18@DigitalLuiggiJus use @bunjavascriptburaksJan 18@buraks____I use bun patch and I love it!fahadaliJan 8@fahadali503BunAiden BaiJan 1@aidenybai2025 will be the year of JS/TS and @bunjavascript is whyCatalinJan 1@catalinmpitBun is goatedMadMaxJan 3@dr__madmax@bunjavascript is yet to get enough appreciation it deserves.Baggi/eJan 3@ManiSohiPerformant TS/JS backend needs more love Elysia for the winMichael FeldsteinDec 18@msfeldsteinholy shit bun is the solution to spending all day mucking around with typescript/module/commonjs/import bullshit and just running scriptsHirbodJan 19@hirbod_devFor everything. Yes. I even run with bunx expo run:ios etcLuis PaoliniJan 18@DigitalLuiggiJus use @bunjavascriptburaksJan 18@buraks____I use bun patch and I love it!fahadaliJan 8@fahadali503BunAiden BaiJan 1@aidenybai2025 will be the year of JS/TS and @bunjavascript is whyCatalinJan 1@catalinmpitBun is goatedMadMaxJan 3@dr__madmax@bunjavascript is yet to get enough appreciation it deserves.Baggi/eJan 3@ManiSohiPerformant TS/JS backend needs more love Elysia for the winMichael FeldsteinDec 18@msfeldsteinholy shit bun is the solution to spending all day mucking around with typescript/module/commonjs/import bullshit and just running scripts

Resources

ReferenceDocsGuidesDiscordMerch StoreGitHubBlog 

Toolkit

RuntimePackage managerTest runnerBundlerPackage runner

Project

Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicenseBaked with ❤️ in San Francisco

We're hiring →

智能索引记录