Revolutionizing JavaScript Runtimes: The Bun Breakthrough

Revolutionizing JavaScript Runtimes: The Bun Breakthrough

What is a JavaScript runtime?

A JavaScript runtime is an environment in which JavaScript code is executed. It provides the necessary infrastructure to interpret and run JavaScript programs. JavaScript runtimes handle tasks like parsing and executing JavaScript code, managing memory, and providing access to various APIs (Application Programming Interfaces) for interacting with the host environment. Depending on the runtime, additional features and APIs may be available, such as file system access in Node.js or DOM manipulation in browser-based runtimes. Here are two common types of JavaScript runtimes:

  • Browser-Based Runtimes: In web browsers, JavaScript code runs in a runtime environment often referred to as the "JavaScript engine." Each major browser has its own JavaScript engine, such as V8 in Chrome, SpiderMonkey in Firefox, and JavaScriptCore in Safari. These engines are responsible for executing JavaScript code on websites, making web applications interactive.
  • Server-Side Runtimes: JavaScript can also be run on servers using runtime environments like Node.js. Node.js is a popular server-side JavaScript runtime that allows developers to build server applications using JavaScript. It uses the V8 JavaScript engine, the same engine that powers Chrome, but adapted for server-side use.

Bun’s anatomy

Bun is an innovative All-in-One JavaScript runtime designed specifically for the modern JavaScript ecosystem. It has been built from scratch and incorporates native-speed functionality developed in the Zig programming language. Zig, a relatively new language introduced in 2016, shares similarities with C and Rust but provides enhanced low-level memory control and eliminates hidden control flow making it much simpler to write fast software.

Bun's logo

Additionally, Bun doesn't use the V8 engine (like Node.Js) but instead uses JAVASCRIPTCORE from WebKit which is generally considered to be faster. One another factor of Bun’s fast performance is its creators focus on implementing native APIs in native code.

Bun can also act as a bundler like Webpack or Veet, as a test Runner like Jest or Karma and as a package manager like npm or yarn.

How Bun is different?

Bun exhibits a substantial speed advantage, approximately three times faster, across various tasks like server-side rendering React, executing database queries, and running native code through foreign functions. To illustrate this performance gap, take a look at the benchmark test results below:

Bun's benchmarking

Bun’s main features

TypeScript and JSX out of the box support

Bun can directly execute .ts, and .tsx files just like vanilla JavaScript, with no extra configuration. When you import a .ts or .tsx file or an npm module that exports these files, Bun internally transpiles them into JavaScript and executes them effortlessly.

Bun comes pre-equipped to handle .jsx files too, with its internal transpiler adeptly transforming JSX syntax into vanilla JavaScript prior to execution.

Compatible with Node.js packages (node_modules)

The bun CLI contains a Node.js-compatible package manager designed to be a dramatically faster replacement for npm, yarn, and pnpm. This standalone tool seamlessly integrates into existing Node.js projects, offering a significant boost to your workflow efficiency when your project contains a package.json file, courtesy of the bun install command.

Native APIs

HTTP server

To start a high-performance HTTP server with a clean API, the recommended approach by the documentation is Bun.serve

Bun.serve({
? port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
? hostname: "mydomain.com", // defaults to "0.0.0.0"
? fetch(req) {
??? return new Response("Hello friend.");
? },
});        

WebSockets

Bun.serve() also supports server-side WebSockets, with on-the-fly compression, TLS support, and a Bun-native publish-subscribe API. Here is a simple WebSocket server built with Bun.serve :

Bun.serve({
? fetch(req, server) {}, // upgrade logic
? websocket: {
??? message(ws, message) {}, // a message is received
??? open(ws) {}, // a socket is opened
??? close(ws, code, message) {}, // a socket is closed
??? drain(ws) {}, // the socket is ready to receive more data
? },
});        

File I/O

Bun provides a set of optimized APIs for reading and writing files.

We can create a BunFile instance with the Bun.file(path) function. A BunFile represents a lazily loaded file; initializing it does not actually read the file from disk.

const foo = Bun.file("foo.txt"); // relative to cwd
foo.size; // number of bytes
foo.type; // MIME type
await foo.text(); // contents as a string        

To write a string to disk:

const data = It was the best of times, it was the worst of times.;
await Bun.write("output.txt", data);        

Environment Variables

Bun automatically parses your .env files and offers user-friendly methods for programmatically accessing and modifying your environment variables.

You can set variables programmatically by assigning a property to process.env.

process.env.FOO = "hello";        

The current environment variables can be accessed via process.env.

process.env.API_TOKEN; // => "secret"        

Bun also exposes these variables via Bun.env, which is a simple alias of process.env.

Bun.env.API_TOKEN; // => "secret"        

In most cases, you can do away with dotenv because Bun now handles .env file reading automatically.

Watch mode

Bun supports two kinds of automatic reloading via CLI flags:

??? --watch mode, which hard restarts Bun's process when imported files change.

??? --hot mode, which soft reloads the code (without restarting the process) when imported files change.

Built-in SQLite Database

Bun natively implements a high-performance SQLite3 driver. To use it import from the built-in bun:sqlite module. The API is simple, synchronous, and fast.

Some of its notable features include:

  • Transactions.
  • Parameters (named & positional).
  • Prepared statements.
  • Datatype conversions (BLOB becomes Uint8Array).
  • The fastest performance of any SQLite driver for JavaScript.

Bun Package Manager

As mentioned earlier, Bun serves as an all-encompassing JavaScript runtime, doubling as a Node.js-compatible package manager. It not only accommodates Node.js packages but also outperforms yarn, npm, and even pnpm due to its optimized file writing.

Installing dependencies from cache for a Remix app.

When it comes to copying files from the cache to node_modules, Bun uses the fastest system calls available on your operating system. This approach significantly surpasses the speed of merely creating symbolic links from a global cache, as seen in pnpm.

Liran Tal

Lead DevRel & Secure Coding advocate ??

1 个月

Nice seeing more Bun news shared if you are venturing into a new JavaScript server runtime like Bun, don't miss out on my new and unique Bun Security resource for developers: https://www.bunsecurity.dev/ Happy to take any comments or questions :-)

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了