15.8 C
New York
Wednesday, November 4, 2026

An Introduction to the Bun JavaScript Runtime — SitePoint


Bun is a rival JavaScript runtime to Node.js and Deno. On this article, we take have a look at Bun 1.0, and the explanations it might tempt you away out of your present favourite.

The unique model of this text was revealed in early 2023. Now that Bun model 1.0 has arrived, we overview whether or not this milestone may have any influence on the present JavaScript champions.

Desk of Contents

The Historical past: The place Bun Suits In with Node and Deno

Ryan Dahl launched Node.js in 2009. It wasn’t the primary server-side JavaScript runtime, however Node.js quickly gained momentum. Model 20 arrived in 2023, and Node.js has the most important growth ecosystem, with 3.2 million modules — accounting for nearly 500 billion downloads per week (based on npmjs.com).

In 2020, Ryan Dahl launched Deno — a remix of “noDe” — to modernize JavaScript growth and handle legacy points with Node.js safety, API compatibility, tooling, and module administration. Reception has been constructive, though Deno is but to problem Node’s domination.

In 2022, Jarred Sumner launched Bun following his frustrations with the velocity of Node.js when growing a Subsequent.js venture.

Bun makes use of the JavaScriptCore engine, which powers WebKit browsers akin to Safari, quite than the V8 engine utilized in Node.js, Deno, and Chrome.

The Bun runtime focuses on efficiency and developer expertise. The goal is to get rid of slowness and complexity with out throwing away every thing that’s nice about JavaScript.

Bun can evolve sooner than Node.js — which should stay (largely) backward-compatible with the prevailing JavaScript and npm ecosystem.

Like Deno, Bun has native help for JavaScript and TypeScript with out requiring a third-party transpiler or configuration.

Bun is turning into a drop-in substitute for Node.js, Deno, serverless runtimes, construct, and testing instruments. It might change npm, npx, yarn, TypeScript compilers, dotenv, nodemon, pm2, Webpack, Babel, and Jest, to offer a whole all-in-one toolbox for growing functions on a single platform.

The unique runtime was steady, however due to contributions from nearly 300 builders, the Bun model 1.0 launch arrived in September 2023. It will inevitably tempt extra builders emigrate to Bun the place they’ll benefit from the advantages described under.

What’s with the title “Bun”?

The origin of the “Bun” title is unclear, and the emblem doesn’t assist! It might relate to the meals, fluffy bunny rabbits, “bundle”, or maybe it’s a brief, memorable title and the bun.sh area was out there.

The Bun logo

Tasty Bun Advantages

Node.js and Deno use Chrome’s V8 JavaScript engine. Bun opts for the JavaScriptCore engine which powers WebKit browsers akin to Safari. Bun itself is written in Zig — a low-level programming language with handbook reminiscence administration and native threading to deal with concurrency. The result’s a light-weight runtime with a smaller reminiscence footprint, faster start-up occasions, and efficiency which will be 4 occasions sooner than Node.js and Deno beneath sure (benchmarking) situations.

Like Deno, Bun has native help for each JavaScript and TypeScript with out requiring a third-party transpiler or configuration. It additionally helps .jsx and .tsx recordsdata to transform HTML-like markup to native JavaScript. Experimental help for operating WebAssembly-compiled .wasm recordsdata is obtainable.

Internally, Bun makes use of ES Modules, helps top-level await, interprets CommonJS, and implements Node’s node_modules decision algorithm. Bun caches modules in ~/.bun/set up/cache/ and makes use of hardlinks to copy them right into a venture’s node_modules listing. All tasks in your system will due to this fact reference a single occasion of the identical library, which reduces diskspace necessities and improves set up efficiency. (Notice that macOS installations retain native variations for velocity.)

Bun helps Node’s bundle.json, npm equal instructions, and bunx — a npx-like choice to auto-install and run packages in a single command. For instance:

bunx cowsay "Hiya, world!"

bun init scaffolds empty tasks in the identical method as npm init, however you may also template a brand new venture with bun create <template> <vacation spot>, the place <template> is an official bundle, a Github repository, or a neighborhood bundle. For instance, to create a brand new Subsequent.js venture:

bun create subsequent ./myapp

Bun features a bundler to import all dependencies right into a single file and may goal Bun, Node.js, and client-side JavaScript. This reduces the necessity to use instruments akin to esbuild or Rollup:

bun construct ./index.ts —outdir ./out

Most command-line interface choices can be found through a JavaScript API, so it’s doable to create subtle construct scripts with out a devoted process runner. Right here’s an equivalent construct to the command above:

await Bun.construct({
  entrypoints: ['./index.ts'],
  outdir: './out',
})

Bun has an ordinary take a look at runner like Deno and Node.js 20. Operating bun take a look at executes scripts named like this:

*.take a look at.ts
*_test.ts
*.spec.ts
*_spec.ts

There’s no want for nodemon-like instruments, since bun has a —watch flag which restarts scripts or exams if you modify a dependency file. Restarts are so quick that it turns into doable to live-reload on every keystroke. (Whether or not that is sensible and never a distraction is one other matter!)

Reside reloading just isn’t fairly! (Warning: flickering content material!) View unique animated GIF.

The same —scorching mode is obtainable, the place Bun watches for adjustments and gentle reloads modules. All recordsdata are re-evaluated, however the international state persists.

Atmosphere variables contained in venture .env recordsdata are routinely loaded and parsed, making them out there in Bun functions, so there’s no want to make use of packages akin to dotenv.

In addition to its personal Bun APIs for networking, file entry, baby processes, and so forth, Bun helps:

  • Internet APIs akin to fetch, URL, blob, WebSocket, JSON, setTimeout, and occasions.

  • Node.js compatibility APIs akin to console, assert, dns, http, path, stream, and util, in addition to globals together with __dirname, and __filename. Bun claims that 90% of the most-used APIs are totally applied, though it’s best to double-check these particular to your venture.

Lastly, Bun has a local SQLite3 consumer — bun:sqlite — which might cut back the variety of dependencies required in some tasks.

Putting in Bun

Bun is obtainable as a single binary you possibly can set up on Linux, macOS, and Home windows WSL utilizing curl:

curl -fsSL https://bun.sh/set up | bash

It may be put in through the Node bundle supervisor:

npm set up -g bun

Or through Brew on macOS:

brew faucet oven-sh/bun
brew set up bun

Or through Docker:

docker pull oven/bun
docker run --rm --init --ulimit memlock=-1:-1 oven/bun

As soon as put in, you possibly can improve Bun utilizing:

bun improve

Or you possibly can uninstall Bun by eradicating the ~/.bun binary and cache listing:

rm -rf ~/.bun

Then replace your shell configuration file (.bashrc, .zshrc, or comparable) to take away ~/.bun/bin references from the $PATH variable.

Utilizing Bun

Bun is dependable if you happen to use it from the beginning of your venture. Pace is best than Node.js, though you’re unlikely to see a major efficiency enhance except your app is doing particular intensive duties such heavy SQLite processing or WebSocket messaging.

Node.js compatibility is sweet for smaller, easier tasks, and I efficiently launched some scripts utilizing bun begin with out making adjustments. Extra advanced functions did fail, with obscure error messages generated deep within the node_modules hierarchy.

Bun vs Deno vs Node.js

Deno addressed lots of Node’s drawbacks, however builders didn’t essentially really feel compelled to modify:

  • Deno didn’t help Node’s third-party modules.
  • Migrating from Node.js to Deno required studying new strategies.
  • Whereas Deno supplied a greater growth expertise, Node.js was ok.

Deno has now added Node.js compatibility choices. That was the best approach to get builders to transition to Deno, however within the meantime, Node.js has adopted a few of Deno’s options, together with ES modules, a local take a look at runner, and a —watch mode.

Bun has taken a special strategy, aiming to be a quick, Node-compatible engine with Deno’s developments. The indicators are promising, however it’s not there but:

  • Efficiency is nice, however few builders complain about Node.js velocity.
  • Compatibility is sweet, however it will likely be a problem to help all Node.js modules in a special JavaScript engine. Can JavaScriptCore sustain with V8 developments with far much less funding?
  • Bun has the potential to interchange your tooling suite, however it’s but to supply the complete vary present in Deno.

Compatibility of Bun with Node.js

Node.js compatibility is usually good for smaller, easier tasks. You might be able to launch some scripts utilizing bun begin as an alternative of npm begin with out making any adjustments.

Bun helps:

  • built-in Node.js modules and APIs akin to fs, path, http, console, assert, and so forth
  • international variables and objects akin to __dirname and course of
  • the Node.js module decision algorithm to find recordsdata in node_modules

Bun 1.0 claims to run “just about any Node.js utility within the wild”. I’m but to be totally satisfied; advanced functions can fail with obscure error messages generated deep inside your third-party modules.

ES Module and CommonJS Compatibility

Bun helps each ESM and CommonJS module programs with top-level await. ESM took a number of years to reach in Node.js and the ecosystem remains to be dominated by CommonJS. With Bun, there’s no want for particular file extensions (.js, .cjs, .mjs) or "sort": "module" in bundle.json. You should utilize import or require() interchangeably in any file!

Internally, Bun interprets all modules to CommonJS and implements Node’s node_modules decision algorithm. Whether or not this works as anticipated is one other matter:

  • ES6 modules are pre-parsed with the intention to resolve additional imports earlier than code is executed. Dynamic imports are doable, however ought to solely be thought-about as a final resort.
  • CommonJS modules load dependencies on demand whereas executing the code. Dynamic imports are much less problematic.

Execution order will be vital in some functions and it’s the explanation Node.js restricts you to EMS or CommonJS in a single file.

Internet APIs

Bun has built-in help for Internet normal APIs out there in browsers, akin to fetch, Request, Response, URL, blob, WebSocket, JSON, setTimeout, and ReadableStream. Deno launched these APIs to its server runtime and it makes internet coding significantly extra constant. Node.js is catching up however options akin to fetch arrived lately in model 18.

Bun APIs

Bun ships with highly-optimized normal APIs for frequent operations akin to file studying, file writing, HTTP serving, SQLite querying, and password hashing.

WebSockets are supported alongside HTTP with out requiring a third-party module akin to ws:

Bun.serve({
  port: 8000,
  fetch(request) {
    return new Response('Hiya from the Bun server!');
  },
  websocket: {
    open(ws) { ... },
    message(ws, knowledge) { ... },
    shut(ws, code, cause) { ... },
  }
});

TypeScript and JSX Help

Like Deno, Bun has a JavaScript transpiler constructed into the runtime. You’ll be able to run JavaScript, TypeScript, JSX, or TSX recordsdata with out third-party dependencies. For instance:

bun index.ts
bun index.jsx
bun index.tsx

Bundle Administration

You should utilize Bun immediately as an npm substitute in any Node.js venture. For instance:

bun set up
bun add <bundle> [--dev|--production|--peer]
bun take away <bundle>
bun replace <bundle>

Bun caches modules in ~/.bun/set up/cache/ and makes use of hardlinks to repeat them right into a venture’s node_modules listing. All tasks in your system due to this fact reference a single occasion of the identical library. This reduces disk house and improves set up efficiency by as much as an element of 30.

Reside Reloading

There’s no want for nodemon-like instruments, for the reason that bun executable has a -watch flag to restart scripts or exams if you modify a file.

The same —scorching mode is obtainable, the place Bun watches for adjustments and gentle reloads modules. All recordsdata are re-evaluated, however the international state persists.

Testing

Bun provides a Jest-compatible bun:take a look at take a look at runner with help for snapshot testing, mocking, and code protection. For instance:

import { take a look at, count on } from "bun:take a look at";

take a look at('2 + 2', () => {
  count on(2 + 2).toBe(4);
});

Migration from Jest or Vitest is straightforward, since imports from @jest/globals or vitest are internally re-mapped to bun:take a look at. It shouldn’t be essential to make code adjustments.

Operating bun take a look at executes scripts named:

*.take a look at.jsx
*_test.jsx
*.spec.jsx
*_spec.jsx

Script Bundling

Bun is a JavaScript and TypeScript bundler and minifier which may goal code for the browser, Node.js, and different platforms. It’s impressed by esbuild and supplies a appropriate plugin API:


Bun.construct({
  entrypoints: ['index.js'],
  outdir: 'construct'
});

Benchmarks illustrate Bun can twice as quick because the Go-compiled esbuild with comparable minification financial savings.

Not like esbuild, Bun doesn’t help CSS bundling, however that’s more likely to arrive given there’s a common plugin API…

Common Plugin API

Bun’s plugin API is common: it really works for each the bundler and the runtime. You’ll be able to outline plugins to intercept imports and carry out customized loading logic. This instance implements the import of .yaml recordsdata:

import { plugin } from "bun";

plugin({
  title: 'YAML',
  async setup(construct) {
    const { load } = await import('js-yaml');
    const { readFileSync } = await import('fs');
    construct.onLoad(yml)$/ , (args) => {
      const textual content = readFileSync(args.path, 'utf8');
      const exports = load(textual content) as File<string, any>;
      return { exports, loader: 'object' };
    });
  },
});

Begin-up and Execution Pace

Utilizing bun run <script> quite than npm run <script> usually launches an utility 150ms sooner. Which may be a small enchancment, however is’s 4x sooner than Node.js and noticeable if you’re operating many instructions and construct scripts. Efficiency enhancements will probably be better when utilizing utilizing TypeScript, as a result of there’s no transpilation step.

Bun additionally makes the next Node.js efficiency claims:

  • 5x sooner than npx
  • 10x sooner at file reads (utilizing Bun.learn())
  • 3x sooner at file writes (utilizing Bun.write())
  • 4x sooner at serving HTTP requests (utilizing Bun.serve())
  • 4x sooner at SQLite queries (utilizing bun:sqlite)
  • 13x sooner than Jest when testing
  • 8x sooner than Vitest when testing

For bundling, Bun is:

  • nearly twice as quick as esbuild
  • 150x sooner than Parcel 2
  • 180x sooner than Rollup with Terser
  • 220x sooner than Webpack

You’re unlikely to see such positive aspects throughout each venture, however Bun ought to enhance your growth expertise.

Experimental Home windows Version

A local construct of Bun will probably be out there for Home windows shortly. It’s extremely experimental and solely helps the JavaScript runtime with out efficiency optimizations. Options such because the bundle supervisor, take a look at runner, and bundler have been disabled till they’re steady.

For the second, Home windows customers can set up Bun on the Home windows Subsystem for Linux — which stays the best choice if you happen to’re doing any heavy JavaScript work.

Abstract: Ought to You Take a Chew from Bun?

Bun is an achieved JavaScript runtime, however Node.js stays the champion for mission-critical tasks or legacy functions. It is best to attempt operating your app utilizing bun begin, however the bigger your codebase, the much less probability it’s going to execute with out modification.

Deno might be a greater possibility than Bun for brand spanking new tasks, on condition that it’s extra mature and feature-complete.

Bun is nice, and being actively developed, however it’s new. The runtime is steady, however few would wager on its long-term future at this stage. That stated, Bun has some attention-grabbing concepts which I hope each the Node.js and Deno groups contemplate adopting (CLI APIs and auto-loaded .env please!)

On a aspect be aware, I like Bun’s title, however it may be troublesome to seek for assets. ChatGPT makes the daring assertion that “There is no such thing as a broadly recognized JavaScript runtime referred to as ‘Bun’. So far as I’m conscious, there isn’t any such know-how within the JavaScript ecosystem.” This can be as a result of post-2021 knowledge is proscribed, though sure questions return a Bun response and an apology for the error!

I think we’re heading towards an age of isomorphic server-side JavaScript, the place module builders try to jot down code that’s appropriate with all runtimes: Node.js, Deno, Bun, serverless, edge, embedded, and so forth. We could finally attain some extent the place JavaScript runtimes are largely interchangeable in the identical method browsers are at this time.

The Bun model 1.0 milestone could also be technically meaningless given the minor adjustments from 0.8. The psychological distinction is bigger: Bun feels extra full and usable. Extra builders will contemplate the runtime and toolset for their very own tasks.

Deno initially went in its personal (good) route however needed to backtrack. It was too radical and too incompatible for a lot of Node.js builders. Switching from Node.js to Deno mid-project nonetheless isn’t one thing it’s best to ponder with out accepting the results.

Bun has supplied compatibility and velocity from the beginning — a substantial achievement given it’s utilizing a special JavaScript engine. Whether or not it achieves one thing near 100% Node.js compatibility stays to be seen, however you would contemplate it as a drop-in substitute for a few of your toolset on legacy tasks.

Bun’s velocity claims are spectacular, however few complain about uncooked Node.js efficiency, particularly when it improves with each launch. Some frameworks are sluggish, however that’s typically owing to bloat quite than an inherent fault of the runtime.

For the second, Node.js stays the undisputed JavaScript champion. Few will get fired for selecting Node.js, however Bun has prevented a few of Deno’s missteps and is quickly turning into a lovely possibility.





Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles