This is a starter repo for Bun.js is a JavaScript runtime, bundler, toolkit. It is designed to be a simple, fast, and easy to use tool for JavaScript developers.
- Introduction
- Bun.js Website
- Install Bun.js
- Getting Started
- Running Modes and Environment Configuration
- Working with Routes and File I/O
- Bun X
- Examples
- Testing and Bundling
- Macros
curl -fsSL https://bun.sh/install | bashSupported on macOS, Linux, and WSL. Windows is not supported yet. See Installation for more details.
When you install Bun.js, you will see something like this:
bun was installed successfully to ~/.bun/bin/bun
Added "~/.bun/bin" to $PATH in "~/.bashrc"
To get started, run:
source /home/milliorn/.bashrc
bun --helpTo test the installation run:
bun --helpand to confirm you can run:
bun --versionSee Quickstart for more details.
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 helps you get started with a minimal project and tries to guess sensible defaults. Press ^C anytime to quit
package name (bun-starter):
entry point (server.ts):
Done! A package.json file was saved in the current directory.
+ server.ts
+ tsconfig.json (for editor auto-complete)
To get started, run:
bun run server.tsSee Run a script for more details.
In your cli in the root of your project run:
bun run server.tsNow, open package.json in your editor. You can add this to your scripts:
{
"scripts": {
"start": "bun run server.ts"
}
}Then run it with bun run start.
bun run startNow, open server.ts in your editor and paste the following code:
console.log("Hello via Bun!");
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Bun!");
},
});
console.log(`Listening on http://localhost:${server.port}`);Now, open http://localhost:3000 in your browser. You should see "Bun!".
See Watch mode for more details.
In your cli in the root of your project run:
bun run --watch server.tsSee Hot Mode for more details.
Use bun --hot to enable hot reloading when executing code with Bun.
bun run --hot server.tsSee Environment variables for more details.
Bun uses the dotenv package to manage environment variables. Create a .env file in the root of your project:
touch .envAdd the following to your .env file:
PORT=3000Now, open server.ts in your editor and replace the port with the following:
port: process.env.PORT || 3001;Should look like this:
console.log("Hello via Bun!");
const server = Bun.serve({
port: process.env.PORT || 3001,
fetch(req) {
return new Response("Bun run!");
},
});
console.log(`Listening on http://localhost:${server.port}`);Alternatively, you can use the bun instead of process.env:
port: Bun.env.PORT || 3001;We can create simple routes:
console.log("Hello via Bun!");
const server = Bun.serve({
port: process.env.PORT || 3001,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("Hello World!");
} else if (url.pathname === "/json") {
return new Response(JSON.stringify({ hello: "world" }), {
headers: { "content-type": "application/json" },
});
} else {
return new Response("Not Found", { status: 404 });
}
},
});
console.log(`Listening on http://localhost:${server.port}`);Now, if you go to http://localhost:3001/json you should see:
{ "hello": "world" }bunx <package> is a command line tool that allows you to run a package without installing it, similar to npx.
bunx cowsay "hello" _______
< hello >
-------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||See File I/O for more details.
Make a new file called writeFile.ts or whatever you want it to be in the root of your project and add the following text:
const dummyData = "Hello World!";
await Bun.write("writeFile.txt", dummyData);If you don't use writeFile.ts as the name of the file, make sure to change the name in the parameter of Bun.write().
Now you can run the code with:
bun run writeFile.tsYou should see a new file called writeFile.txt in the root of your project with the text "Hello World!".
To read the file, make a new file called readFile.ts or whatever you want it to be in the root of your project and add the following text:
const readFlie = Bun.file("writeFile.txt");
console.log(await readFlie.text());bun-starter$ bun run readFile.ts
[3.24ms] ".env"
Hello World!See bun test for more details.
Bun.js comes with a built-in test runner. To run tests, create a file called index.test.ts or whatever you want it to be in the root of your project and add the following text:
import { describe, expect, test, beforeAll } from "bun:test";
describe("math", () => {
test("logic", () => {
expect(1).toBe(1);
});
});Now you can run the code with:
bun testYou should see:
math
✓ logic
1 passing (1ms)See Bundler for more details.
Bun.js comes with a built-in bundler. To bundle your code, create a file called index.ts or whatever you want it to be in src folder of your project and add the following text:
import axios from "axios";
async function fetchUser(user: string) {
try {
const response = await axios.get(`https://api.github.com/users/${user}`);
return response.data;
} catch (error) {
console.error("Error fetching user:", error);
throw error;
}
}
fetchUser("milliorn")
.then((data) => console.log("User data:", data))
.catch((error) => console.error("Error:", error));Now you can bundle the code with:
bun build src/index.ts --outfile dist/bundle.jsYou should see a new file called bundle.js in the dist folder of your project with the bundled code.
See Macros for more details.
Macros are a mechanism for running JavaScript functions at bundle-time. The value returned from these functions are directly inlined into your bundle.
Create a file called random.ts or whatever you want it to be in src folder of your project and add the following text:
export function random() {
return Math.random();
}Now you can use the macro in cli.tsx:
import { random } from './random.ts' with { type: 'macro' };
console.log(`Your random number is ${random()}`);Now you can bundle the code with:
bun build src/cli.tsxAt the time of this writing TypeScript does not support macros as it will throw linter errors. It will work.