Starting with Bun : The Fastest JavaScript Runtime
Tags: javascript
Published: 2023-09-14 16:06:41

What is Bun may ask.

Bun offers a comprehensive toolkit tailored for JavaScript and TypeScript applications, encapsulated within a singular executable named 'bun'.

Central to its design is the Bun runtime, an optimized JavaScript runtime crafted to seamlessly substitute Node.js. Engineered in Zig and anchored by JavaScriptCore, it significantly trims down both startup durations and memory consumption.

As they claim 
- Bun is a fast JavaScript package
- Bun is a fast JavaScript package manager
- Bun is a fast JavaScript bundler

Here's a brief summary of article:

- **Nature of Bun**: Bun is multifaceted, acting as a rapid JavaScript package, package manager, and bundler.

- **Compatibility**: Currently, Bun is exclusively supported on macOS, Linux, and WSL. For Windows users, a Linux virtual machine setup is necessary.

- **Installation**: Users can easily install Bun using the provided curl command. There are visual aids in the form of screenshots to assist users throughout the installation process.

- **Building a Server**: The article offers a step-by-step guide on creating a basic HTTP server using Bun's native API. The server is initiated on port 3000 and displays a message "Bun!" when accessed.

- **Script Execution**: Like Node.js, Bun can run "scripts" from the `package.json` file. The article provides a sample `package.json` setup for reference.

- **Using Express with Bun**: The integration of Bun with the popular web application framework, Express, is explored. A basic server setup using Express is provided, which displays a "Hello World!" message.

- **Server-side Rendering with React**: Delving deeper into more advanced applications, the article showcases how to perform server-side rendering of a React component using Bun. This section provides a React component sample, and how it can be rendered on the server side and sent as pre-rendered HTML elements.

- **Conclusion**: While Bun is still in its early phases of development, it shows considerable potential as a tool in the JavaScript domain.

The article concludes with further reading suggestions, providing resources on various applications and perspectives on Bun.

As they claim 
- "Bun is a fast JavaScript package"
- Bun is a fast JavaScript package manager
- Bun is a fast JavaScript bundler

#### Installation
Let's install this bad boy. Unfortunately, Bun is supported only on macOS, Linux, and WSL. If you have Windows machine then you have to install Linux virtual machine as I did.

Run this command `curl -fsSL https://bun.sh/install | bash`
![ubuntu terminal](https://eneaslari.com/7104eb07-e970-4113-bb99-114f3be7dbe2.PNG "image of ubuntu terminal")

Let's write a simple HTTP server using the built-in Bun.serve API. First, create a fresh directory.

Run `bun init` to scaffold a new project. It's an interactive tool; for this tutorial, just press enter to accept the default answer for each prompt.

![Bun init](https://eneaslari.com/e20503e2-3057-415e-a747-a44dc4c6e47d.PNG "Bun init screenshot")

#### Run a file
Open `index.ts` and paste the following code snippet, which implements a simple HTTP server with Bun.serve.

```javascript
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Bun!");
  },
});

console.log(`Listening on http://localhost:${server.port} ...`);
```
Run the file from your shell:
`bun index.ts`

Output:
`Listening on http://localhost:3000 ...`

![Bun index.ts](https://eneaslari.com/e781e5c7-bf7e-4d8e-8a2a-4c6c51345c81.PNG "Bun index.ts screenshot")

Visit http://localhost:3000 to test the server. You should see a simple page that says "Bun!".

![Bun index.ts](https://eneaslari.com/cb8c1bbf-adf4-4143-b45c-35c9afdba1d6.PNG "Bun index.ts screenshot")

#### Run a script
Just like Node.js , Bun can also execute "scripts" from your package.json. Add the following script:
```
{
  "name": "firstbun",
  "module": "index.ts",
  "type": "module",
  "scripts": {
    "start": "bun run index.ts"
  },
  "devDependencies": {
    "bun-types": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  }
}
```
Then run it with bun run start.

`bun run start`
  $ bun run index.ts
Listening on http://localhost:3000...

#### Build an HTTP server using Express and Bun

But first lets switch to javascript instead of typescipt (personal preference).
Remove `tsconfig.json` and rename `index.ts` to `index.js`

Express and other major Node.js HTTP libraries should work out of the box. Bun implements the node:http and node:https modules that these libraries rely on.

```javascript
import express from "express";

const app = express();
const port = 8080;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log(`Listening on port ${port}...`);
});
```
#### Server-side render (SSR) a React component with Bun

Now for the fun part. Lets use the react and jsx syntax to send some pre rendered HTML elements

First create a react component:

`helloworldcomp.jsx`

```javascript

export function MessageComponent({message}) {
  return (
    <h1>
      {message}
    </h1>
  );
}

```
Then on our server file index.js

```javascript
import express from "express";
import ReactDOMServer from "react-dom/server"
import { MessageComponent } from "./helloworldcomp";


const app = express();
const port = 3000;

app.get("/", async (req, res) => {
  const htmlstring = await ReactDOMServer.renderToString(<MessageComponent message='Hello World!' />);
  res.send(htmlstring);
});

app.listen(port, () => {
  console.log(`Listening on port ${port}...`);
});
```
![alt text](https://eneaslari.com/27db273a-17fd-4dd6-88eb-71cdd4aa6d91.PNG "How nodejs work under the hood")


That's it for now. Bun is really on early stages but seems promising. 

Thank you for your time,

Eneas

Other sources:

[How to Write an Express-like API Using Bun.js](https://betterprogramming.pub/write-a-express-like-api-using-bunjs-79e77a6a7a31)

[Server-side render (SSR) a React component with Bun](https://bun.sh/guides/ecosystem/ssr-react)

[Bun: The Next Big Thing in Javascript](https://dev.to/kalashin1/bun-the-next-big-thing-in-javascript-jeg)

[Basics of React server-side rendering with Express.js](https://dev.to/juhanakristian/basics-of-react-server-side-rendering-with-expressjs-phd)