Getting Started With Bun

Getting Started With Bun

Getting Started With Bun

What is Bun?

Bun is an all-in-one JavaScript runtime & toolkit designed for speed, complete with a bundler, test runner, and Node.js-compatible package manager. It’s written in Zig. Under the hood it is using JavaScriptCore(developed by Apple) compared to v8(developed by Google) which is used by Nodejs.

Bun vs Node vs Deno

Bun is runtime similar to Node and Deno. Unlike deno and node, Bun is built on JavaScriptCore. Node and Deno use V8 as their primary JavaScript execution engines. It directly execute .jsx, .ts, and .tsx files; Bun’s transpiler converts these to vanilla JavaScript before execution. Bun both supports ES modules and CommonJS. In addition to supporting Node-style module resolution, Bun aims for full compatibility with built-in Node.js globals (process, Buffer) and modules (path, fs, http, etc.)

Installation

To install Bun execute following:

curl -fsSL https://bun.sh/install | bash # for macOS, Linux, and WSL
# to install a specific version
curl -fsSL https://bun.sh/install | bash -s “bun-v1.0.0”

Quickstart

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

bun init helps you get started with a minimal project and tries to
guess sensible defaults. Press ^C anytime to quit.
package name (helloworld):
entry point (index.ts):
Done! A package.json file was saved in the current directory.

  • index.ts
  • .gitignore
  • tsconfig.json (for editor auto-complete)
  • README.md
    To get started, run:
    bun run index.ts

Since our entry point is a *.ts file, Bun generates a tsconfig.json for you. If you’re using plain JavaScript, it will generate a jsconfig.json instead.

Run a file

Open index.ts and paste the following code snippet, which implements a simple HTTP server with Bun.serve. Bun global object and through a number of built-in modules. Bun introduces new APIs primarily for server-side tasks where no standard exists, such as file I/O and starting an HTTP server.

const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response(“Hello From Bun!”);
},
});

console.log(`Listening on http://localhost:${server.port} …`);

Run the file from your shell.

bun index.ts

Listening on http://localhost:3000 …

Run a script

Bun can also execute “scripts” from your package.json. Add the following script:

“scripts”: {
“start”: “bun run index.ts”
},

Then run it with bun run start.

Node.js compatibility

Most npm packages intended for Node.js environments will work with Bun out of the box; the best way to know for certain is to try it. For instance node:path

const path = require(‘node:path’);
console.log(path.basename(’./hello/myfile.html’))

For more check it out here.

Environment variables

Bun reads the following files automatically (listed in order of increasing precedence).

  • .env
  • .env.production or .env.development (depending on value of NODE_ENV)
  • .env.local

For instance suppose .env file like this:

FOO=hello
BAR=world

And you can import directly in .tsfile like this

console.log(process.env.FOO, process.env.BAR);

Variables can also be set via the command line.

FOO=helloworld bun run dev

you won’t need dotenv anymore, because Bun reads .env files automatically.

Watch Module

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.

To run a file in –watch mode:

bun –watch index.ts

Package Manager

The bun CLI contains a Node.js-compatible package manager designed to be a dramatically faster replacement for npm, yarn, and pnpm. It’s a standalone tool that will work in pre-existing Node.js projects; if your project has a package.json, bun install can help you speed up your workflow.

To install all dependencies of a project:

bun install

Running bun install will:

  • Install all dependencies, devDependencies, and optionalDependencies. Bun does not install peerDependencies by default.
  • Run your project’s {pre|post}install and {pre|post}prepare scripts at the appropriate time. For security reasons Bun does not execute lifecycle scripts of installed dependencies.
  • Write a bun.lockb lockfile to the project root.

To install in production mode (i.e. without devDependencies or optionalDependencies):

bun install –production

To add a particular package:

bun add zod

import { z } from “zod”;

const stringSchema = z.string();
stringSchema.parse(“Hello World!”); // => “Hello World!”
stringSchema.parse(1); // => throws ZodError

Performance indexing for Bun(HTTP)

Bun demonstrates strong performance capabilities and appears to be a runtime that can rival Rust and Go when it comes to handling HTTP tasks.

Detailed description on various tests: https://www.priver.dev/blog/benchmark/go-vs-rust-vs-bun-vs-node-http-benchmark/

Summary

In this blog we have explored Bun and it’s compatibility with Nodejs. From here the sky is the limit. Hopefully this blog can help you get started in the world of Bun. And this blog is just basic starter of Bun, will write more in upcoming blogs. HTTP benchmark of Bun with node, Rust and Go is here.

Write a comment
No comments yet.