Loading.....

Back to blog
By Priyansu Choudhury Full Stack Developer
Published On: September 27, 2023

Bun 1.0: A Game-Changing Node.js Alternative

Software Development

Just when you thought you'd reached the zenith of development speed, along comes Bun 1.0 to whisk us away to a whole new realm of JavaScript and TypeScript wizardry. In a world where every millisecond counts, Bun is the magic wand that makes your code run, build, test, and debug faster than ever before.

Buckle up, because you're about to take a thrilling ride through the world of Bun 1.0!

Bun 1.0  Node.js Alternative

Why Bun?

JavaScript is fantastic! It's a mature language with a dynamic and passionate developer community that keeps evolving rapidly. But, here's the catch.

Over the past 14 years since Node.js made its debut, we've seen a pile-up of tooling on tooling. And just like any system that grows without a clear plan, the JavaScript tooling landscape has become sluggish and overly complicated. Bun's mission is to simplify and turbocharge the development process without sacrificing all the fantastic things about JavaScript.

Imagine keeping all your favorite libraries and frameworks while bidding farewell to the sluggishness and complexity that has piled up over the years.

Bun is the fresh breeze that promises to make JavaScript development faster, simpler, and more exciting than ever before!

What Makes Bun A Better Choice?

Bun isn't just a toolkit, it's a game-changer. It waltzes in as a drop-in Node.js alternatives, waving goodbye to Node, npx, dotenv, and a whole army of other tools you thought you couldn't live without. With Bun, it's like having your own personal assistant for everything: running, building, testing, and debugging. It's a JavaScript bundler that scoffs at the lethargy of esbuild and the complexity of webpack. Package management? Bun does it seamlessly, reading your package.json like a pro. And testing? Say farewell to jest, ts-jest, and their entourage. Bun is a Jest-compatible test runner that brings speed, simplicity, and reliability to the table. In a world where your code doesn't get parsed three times over, Bun is the hero we've been waiting for, a single integrated toolkit that delivers a best-in-class developer experience, saving you from the fragility and chaos of tool mishmashes.

Elephant In The Room: Speed

Bun is fast, starting up to 4x faster than Node.js. This difference is only magnified when running a TypeScript file, which requires transpilation before it can be run by Node.js.

Bun 1.0 Speed

Unlike Node.js and other runtimes that are built using Google's V8 engine, Bun is built using Apple's WebKit engine. WebKit is the engine that powers Safari and is used by billions of devices every day. It's fast, efficient, and has been battle-tested for decades.

The Magic

  • TypeScript and JSX support: Bun has a JavaScript transpiler that's baked into the runtime. That means you can run JavaScript, TypeScript, and even JSX/TSX files, no dependencies needed.
  • ESM & CommonJS compatibility: Bun supports both module systems, all the time. No need to worry about file extensions, .js vs .cjs vs .mjs, or including "type": "module" in your package.json.Using import and require(), in the same file just magically works.
  • Web APIs: Bun has built-in support for the Web standard APIs that are available in browsers, such as fetch, Request, Response, WebSocket, and ReadableStream.
  • Hot Reloading: Unlike tools like nodemon that hard-restart the entire process, Bun reloads your code without terminating the old process. That means HTTP and WebSocket connections don't disconnect and the state isn't lost. You can run Bun with - -hot to enable hot reloading.

Bun APIs

In contrast to Node.js APIs, which only exist for backwards compatibility, Bun native APIs are quick and simple since they are highly optimized.

Bun.file( )

Using Bun.file() will lazily load a File at a particular path.


                    const file = Bun.file("package.json");
                    const contents = await file.text();

It will return a BunFile, which extends the Web standard File. The file contents can be lazily loaded in various formats.


              const file = Bun.file("package.json");
              
              await file.text(); // string
              await file.arrayBuffer(); // ArrayBuffer
              await file.blob(); // Blob
              await file.json(); // {...}
              

Bun reads files 10x times faster than Node.js.

Bun.write( )

Bun.write( ) is a single, flexible API for writing almost anything to disk — string, binary data, Blobs, even a Response object.

                
          await Bun.write("index.html", "<html />");
          await Bun.write("index.html", Buffer.from("\<html />"));
          await Bun.write("index.html", Bun.file("home.html"));
          await Bun.write("index.html", await fetch("https://example.com/"));
                
              

Bun writes files 3x faster than Node.js.

Bun.serve( )

Bun.serve() is used to spin up an HTTP server, WebSocket server, or both. It's based on familiar Web-standard APIs like Request and Response.

                
                Bun.serve({
                port: 3000,
                fetch(request) {
                return new Response("Hello from Bun!");
                },
                });
              
            

Bun can serve 4x more requests per second than Node.js.

Web Sockets

Bun can support websockets in addition to HTTP by defining an event handler inside the websocket. When compared to Node.js, which lacks a native WebSocket API and necessitates a third-party dependency like ws,

              
                Bun.serve({
                fetch() { ... },
                websocket: {
                open(ws) { ... },
                message(ws, data) { ... },
                close(ws, code, reason) { ... },
                },
                });
              

Bun serves 5x more messages per second than ws on Node.js.

Bun:sqlite

Bun has built-in support for SQLite. It has an API that's inspired by better-sqlite3, but is written in native code to be faster.

                
                import { Database } from "bun:sqlite";
                
                const db = new Database(":memory:");
                const query = db.query("select 'Bun' as runtime;");
                query.get(); // => { runtime: "Bun" }
              

Bun can query SQLite up to 4x faster than better-sqlite3 on Node.js.

Bun.password

Bun.password can hash and verify passwords without using external dependencies like bcrypt or argon2.

                
              const 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);
              // => true
              

Bun - A Package Manager

Your development process might be sped up by Bun's integrated package manager. The days of watching the npm spinner while your dependencies installed are long gone.

                
                  bun install
                  bun add  [--dev|--production|--peer]
                  bun remove 
                  bun update 
                  
                

— but it doesn't feel like them.

Install Speeds

Compared to npm, yarn, and pnpm, bun is much faster. It makes use of the quickest system calls offered by the operating system and employs a global module cache to prevent repeated downloads from the npm registry.

Bun Install Speeds

Running Scripts

If you have run scripts directly with node.js like

npm run dev

You can just replace npm run with bun run to save 150 ms every time you run a command. All of these figures might appear insignificant, but when CLIs are used, the visual difference is substantial. Compared to bun run, running npm run is noticeably sluggish. Also, I’m not simply criticizing npm. In actuality, bun run

Bun is a bundler

Bun is a JavaScript and TypeScript bundler and minifier that can be used to bundle code for the browser, Node.js, and other platforms.

                
                  bun build ./index.tsx --outdir ./build
                
              

It's heavily inspired by esbuild and provides a compatible plugin API.

                
                  import mdx from "@mdx-js/esbuild";
                  Bun.build({ 
                  entrypoints: ["index.tsx"], 
                  outdir: "build", 
                  plugins: [mdx()],
                  });
                
              

Bun's plugin API is universal, meaning it works for both the bundler and the runtime. So that .yaml plugin from earlier can be used here to support .yaml imports during bundling. Using esbuild's own benchmarks, the results are astonishing

Bun is a bundler

Bundling 10 copies of three.js from scratch, with sourcemaps and minification. Since Bun's runtime and bundler are integrated, it means that Bun can do things that no other bundler can do.

Bun introduces JavaScript macros, a mechanism for running JavaScript functions at bundle-time. The values returned from these functions are directly inlined into your bundle.

                
                  import { getRelease } from "./release.ts" with { type: "macro" };
                  
                  // The value of `release` is evaluated at bundle-time,
                  // and inlined into the bundle, not run-time.
                  const release = await getRelease();
                  
                  
                  bun build index.ts
                  // index.ts
                  var release = await "bun-v1.0.0";
                
              

This is a new paradigm for bundling JavaScript.

Transform your vision into powerful software solutions with our expert development team.

Conclusion - Bun More Thing…

Bun offers native builds for macOS and Linux, but Windows was conspicuously absent. For the first time an experimental native build of Bun for Windows is introduced. Windows Subsystem for Linux now no longer needs to be installed in order to run Bun on Windows.

Bun 1.0 Blog Conclusion

The Windows build of Bun is very experimental, whereas the macOS and Linux builds are ready for production. Only the JavaScript runtime is currently supported; the bundler, package manager, and test runner have been turned off until they are more reliable. Additionally, the performance hasn't yet been optimized. Over the upcoming weeks, support for Windows will be rapidly improved.

Related Blog

Menu

Contact Us

110 Tower-1, Assotech Business Cresterra,
Sector-135, Noida
+91-0120-4100427, +91-9999242821

DRABITO TECHNOLOGIES

Copyright ©2023-2024 | DRABITO TECHNOLOGIES | All Rights Reserved.