Getting Started with Bun: The Ultimate Guide

Getting Started with Bun_ The Ultimate Guide _ MediaOne Marketing Singapore

Introduced in 2022, Bun is a new JavaScript runtime that is quickly gaining traction among developers. It’s an exciting choice of JS runtime because Jarred Summer (the programmer behind it) took all the slow, heavyweight parts of JavaScript runtime and rewrote them, making it extremely fast in most case scenarios. 

Suffice it to say, it’s designed for speed and efficiency and comes complete with a bundler, test runner, and Node.js compatible package manager.

You can use Bun JS to develop front-end and back-end applications, as it supports both the client and server side of web development. It also provides out-of-the-box support for popular tools like React, GraphQL, Webpack, Babel, Typescript, and more.

Bun JS has three major design goals:

  • Speed: Bun starts and runs fast. It extends JavaScriptCore, the JavaScript engine used by Apple’s Safari browser, and optimises it for performance. As computing power increases, Bun can take advantage of it, giving you faster speeds.
  • Elegant APIs: Bun provides a minimal set of highly optimised APIs for performing online tasks, such as HTTP server requests, I/O operations, and file writing. 
  • Cohesive DX: Bun comes with a suite of tools and libraries that make development easier. It has a built-in bundler for packaging assets, a test runner for debugging functions, and a complete suite of other features to help you build a fully functional app.

It’s designed as a drop-in replacement for Node.js, so if you’re already familiar with Node.js, Bun will be a breeze to learn and use. It natively implements hundreds of Node.js modules and Web APIs, including fs, Buffer, path, process and more. Bun also supports native modules, so you can easily extend its capabilities with your own custom code.

Bun’s goal is to run most of the world’s JavaScript applications without sacrificing performance. With its focus on speed and convenience,  Bun is perfect for developing high-performance, low-latency applications. So, if you’re looking to take your web development to the next level, then perhaps you should consider giving Bun a short.

Let’s paint a few Scenarios for Bun — Like When Can You Use It and How’s It Different from Node and Deno.

Bun Vs. Node Vs. Deno – When to Use Each

Bun, much like Node.js and Deno, is a JavaScript runtime environment. It’s designed for speed and ease of use, and it’s trying to be compatible with most Node.js modules and Web APIs, so it’s perfect for most web applications.

However, unlike Node and Deno, Bun is built on top of Safari’s JavaScriptCore engine and optimised for low-latency applications (whereas Node and Deno are built on Google’s V8 engine, which is optimised for throughput). That means that Bun will be faster than either of them in scenarios where performance matters.

Remember, JavaScript engines are only supposed to run JavaScript code. However, Bun features a lot of baked-in tooling and other features that improve its speed and overall performance.

On its performance, Bun maintainers provide a benchmark example, running an HTTP handler that renders a server-side page with React. Bun handled about 68,000 requests/second compared to 14,000 for NodeJS and 29,000 for Deno.

That’s quite impressive, considering that Bun is only a year old. 

You can follow Jared Summer on Twitter, where he regularly updates about recent developments on Bun. He also shares a lot of tips and best practices for web development.

Bun also includes task-running and bundling features for JavaScript and TypeScript-based projects. Also, like Deno, it ships single binaries, making it easy to install and use for most projects. 

It also features Web API support, meaning you can call built-in APIs, like `fetch` or the `location` object, without installing additional modules.

Finally, it’s worth mentioning that it supports most Node.js libraries with proper compatibility and type-checking with TypeScript. So, you don’t need to rewrite existing code for Bun. That’s a great time saver! 

Performance

Bun’s superiority is undeniable. As discussed earlier, its performance prowess is evident in the number of requests it can manage per second – a feat that’s hard to ignore. This prowess extends to database operations as well. Let’s consider the average queries per second when handling the Northwind database for SQLite. Bun uses that as a benchmark example, and here’s how things go:

Table 1:

Run Time Queries/second 
BunJS  81.37
Deno 43.50
Node  21.29

In a further performance comparison among Node.js, Deno, and Bun, Bun handles concurrent connections at an astonishing speed. To illustrate, Bun effortlessly reaches 110,000 requests per second with ten concurrent connections. In contrast, Node.js and Deno lag, achieving 60,000 and 67,000 requests per second, respectively.

That performance disparity remains consistent as the number of concurrent connections increases, demonstrating the clear difference in runtime performance between the three.

ALSO READ
18 Ways to SEO Your Shopify Website

Despite some debates surrounding the efficacy of the scenarios used for performance tests, Bun consistently comes out on top. Node.js, unfortunately, lags behind in every comparison, underperforming particularly in database speed. Deno and Node.js don’t display a significant disparity in general performance, but Bun overshadows both significantly. 

While Node.js is admittedly lagging, it’s worth noting that efforts are being made to improve its performance. Yagiz Nizipli is at the helm of these improvement initiatives, focusing on several aspects within Node.js. For example, he’s spearheading endeavours to ramp up URL parsing speeds by a staggering 80-90%. These efforts signal a promising future for Node.js, indicating a potential for it to close the performance gap with its peers.

You can carry out performance tests for Bun in your own setup to gauge its efficiency in certain scenarios. These include:

Loading a large database table

The developer team has been laser-focused on enhancing Bun’s speed, leveraging JavaScriptCore — the same engine powering Safari. On the other hand, Deno and Node.js utilise the V8 JavaScript engine, identical to the one running under Chrome’s hood. To further turbocharge Bun, there’s an ongoing initiative to remove dead code from compiled binaries  — a strategy that’s been partially rolled out so far.

In addition to its impressive running speed, Bun is also engineered to launch swiftly—its goal is to maintain high performance even when multiple instances are spun up. 

That makes it an ideal choice for applications that need to scale dynamically. Whether you’re facing an unexpected surge in traffic and need to establish instances rapidly, Bun’s design is purposefully crafted to ensure your services are up and running at the earliest.

Support and Community

While all three projects — Node.js, Deno, and Bun – are open source, there are distinctions in their support structures. Node.js is strictly based on community and volunteer contributions and enjoys backing from the OpenJS Foundation. Contrarily, Deno and Bun derive their support from for-profit organisations and are sustained by projects backed by venture capital.

Node.js boasts a mature ecosystem and extensive community, where you’ll find online help for virtually any scenario. On the flip side, Deno and Bun are newer kids on the block. Hence, the support resources aren’t as voluminous. That said, they have vibrant developer communities eager to impart their wisdom. It’s worth mentioning that Deno’s 1.28 version brought enhanced compatibility with npm packages, smoothing the transition path for developers coming from a Node.js background.

Here is a snapshot of the frequency of tagged questions for each runtime on Stack Overflow, as recorded in September 2023:

Runtime  Questions Tagged 
Node.js  466,762          
Deno     917              
Bun      52               

As the table illustrates, Node.js has an enormous lead regarding tagged questions. This prominent presence increases your chances of discovering an identical or related query or receiving a suitable solution to your issues.

A developer survey, known as the State of JavaScript, is conducted every year. One of the questions in the survey pertains to the runtimes that participants use regularly. The survey attracted close to 30,000 participants. Data from the latest survey in 2022 reveals Node.js as the undisputed leader, followed by Deno with approximately 5300 votes and Bun garnering around 1,200 votes. Given the current landscape, this distribution stands to reason, but monitoring how these figures evolve in the forthcoming 2023 survey results will be intriguing. Perhaps we might observe emerging trends favouring Deno and Bun.

Deno’s manual is jam-packed with valuable resources to help you familiarize yourself with the runtime and integrate it into your projects. Right on the homepage, you’ll find clear links to the installation guide and extensive documentation, sparing new users the hassle of searching for help. It also provides insights into the standard library that you can utilize immediately. The third-party modules page, a helpful directory outlining available tools in the ecosystem, is another valuable resource. As of August 2023, it boasts over 6,000 modules, complete with example code.

Bun’s home page prominently features connections to its Discord, documentation, and GitHub pages. Since their initial roll-out, the documentation has undergone substantial improvements. There now exists an elaborate, dedicated site brimming with informative content on various subjects. That includes guidance on getting started, using the bundler and test runner, and an API reference. 

Stability

As an entrenched entity in the landscape, Node.js boasts tried-and-true performance, fueling 2.1 percent of global websites. It’s a familiar asset with many projects utilizing its capabilities. Moreover, if you encounter a hiccup along the way, solutions are likely readily available, given its widespread usage.

website design banner

Deno reached its milestone with the release of version 1.0 in May 2020, marking the first stable version of the runtime. Yet, the adoption has been somewhat sluggish, possibly due to a lack of distinctive features that could appeal to developers on a large scale. 

ALSO READ
24 Tried-and-Tested Tips To Be An Outstanding Web Designer Today

get low cost monthly seo packages

Since achieving its 1.0 version, Deno has made considerable progress in enhancing the user experience while maintaining a steady environment with each new release. That ensures that developers can transition to updated versions with minimal to non-existent disruptions.

At the time of writing, Bun is in its beta phase, specifically version 0.7.3, but is rapidly approaching its anticipated 1.0 version release planned for September 2023. Consequently, there has been a noticeable enhancement in both its stability and the extent of its Node.js core APIs since its beta release. This trend is likely to persist as it garners more interest from the community and finds its way into more projects.

engaging the top social media agency in singapore

Security

Security concerns related to dependency management with npm and broader application security issues in Node.js can present significant challenges. Deno was developed with a strong focus on bolstering security, offering granular access control for sensitive APIs like network requests and file system functions. These protective measures are central to Deno’s appeal. Meanwhile, Node.js has also evolved its security offerings. The introduction of a permissions model in Node.js 20, akin to Deno’s, allows for similar fine-tuned security controls, ensuring that Node.js keeps pace in the security arena.

A wealth of resources exists to guide you in learning safe practices. Take, for example, the article on Node.js security best practices by Snyk and the OWASP cheat sheet. The Node.js Foundation has also created resources to help developers understand and use secure coding practices.

Deno addresses some of the security issues found in Node.js by mandating explicit permissions for specific actions within a functioning application. For example, to allow your application to read from the file system, launch it with the –allow-read flag. A comprehensive list of these permissions can be found in their documentation. This permission system can be manipulated during runtime, permitting you to request and revoke permissions programmatically. However, caution is advised when using the –allow-run flag for its subprocesses, as they do not share the same security limitations as the Deno process. That could potentially undermine Deno’s security sandbox and lead to privilege escalation.

psg digital marketing

Bun is still in its infancy, and it can be hard to find detailed information about its security. Given its nascent stage, it’s advisable to use Bun cautiously and stay abreast of any updates or announcements regarding security improvements. As it achieves greater stability, there are intentions to implement security audits.

How to Install Bun

It’s a relatively straightforward process for Linux or macOS users to get Bun up and running on your system. Simply input `curl https://bun.sh/install | bash` into your command line interface (CLI), and you’re ready to go. 

However, for Windows users, the situation is a bit different. As of now, Bun does not support direct installations on Windows OS. But don’t worry, there’s a workaround.

You can still utilize Bun on Windows by leveraging the Windows Subsystem for Linux (WSL). Your first step will be to activate WSL on your Windows 10 machine.

How to Install Bun on Windows 10

As we said, you must enable WSL on your Windows 10 computer.

All you have to do is find “Turn Windows features on or Off” in your computer’s settings. Alternatively, just type it in the Windows search.

Next, scroll down until you find “Windows Subsystem for Linux” and check the box before it.

 The next thing you want to do after that is install Ubuntu. 

To do that, head over to “Microsoft Store” and find the latest Ubuntu LTS version. Ubuntu 22.04.1 LTS is about 681.5MB. 

Proceed to install it by clicking Get.

You’ll be prompted for a username and password. Enter your preferred username and password and proceed to Install Bun.

Installing Bun

Install the ‘unzip’ tool in the Ubuntu terminal. 

Use the “sudo apt install unzip” command as shown in the figure below: 

Next, copy-paste the command for Bun installation, ‘curl https://bun.sh/install | bash’. 

Next, you want to copy-paste the path for Bun on bashrc file. 

The output will look something like this:

Next, you want to open .bashrc and edit it. 

You can use VS Code for this. Just type ~/.bashrc. 

Finally, you can check if Bun is installed by checking its version. Run this command on the terminal bun -version.

But before you do that, you must exit and reopen the Ubuntu terminal.

The output must return the Bun version you installed. 

About the Author

Tom Koh

Tom is the CEO and Principal Consultant of MediaOne, a leading digital marketing agency. He has consulted for MNCs like Canon, Maybank, Capitaland, SingTel, ST Engineering, WWF, Cambridge University, as well as Government organisations like Enterprise Singapore, Ministry of Law, National Galleries, NTUC, e2i, SingHealth. His articles are published and referenced in CNA, Straits Times, MoneyFM, Financial Times, Yahoo! Finance, Hubspot, Zendesk, CIO Advisor.

Share:

Search Engine Optimisation (SEO)

Search Engine Marketing (SEM)

Social Media

Technology

Branding

Business

Most viewed Articles

How to Use SELF in Python

Python, oh Python! It’s a language loved by many for its simplicity and flexibility. One of the key features that sets Python apart is its

Other Similar Articles