diff options
Diffstat (limited to 'docs/guides')
30 files changed, 874 insertions, 22 deletions
diff --git a/docs/guides/ecosystem/elysia.md b/docs/guides/ecosystem/elysia.md new file mode 100644 index 000000000..b0231ff95 --- /dev/null +++ b/docs/guides/ecosystem/elysia.md @@ -0,0 +1,31 @@ +--- +name: Build an HTTP server using Elysia +--- + +[Elysia](https://elysiajs.com) is a Bun-first performance focused web framework that takes full advantage of Bun's HTTP, file system, and hot reloading APIs. Get started with `bun create`. + +```bash +$ bun create elysia myapp +$ cd myapp +$ bun run dev +``` + +--- + +To define a simple HTTP route and start a server with Elysia: + +```ts#server.ts +import { Elysia } from 'elysia' + +const app = new Elysia() + .get('/', () => 'Hello Elysia') + .listen(8080) + +console.log(`🦊 Elysia is running at on port ${app.server.port}...`) +``` + +--- + +Elysia is a full-featured server framework with Express-like syntax, type inference, middleware, file uploads, and plugins for JWT authentication, tRPC, and more. It's also is one of the [fastest Bun web frameworks](https://github.com/SaltyAom/bun-http-framework-benchmark). + +Refer to the Elysia [documentation](https://elysiajs.com/quick-start.html) for more information. diff --git a/docs/guides/ecosystem/express.md b/docs/guides/ecosystem/express.md new file mode 100644 index 000000000..55bd468bd --- /dev/null +++ b/docs/guides/ecosystem/express.md @@ -0,0 +1,40 @@ +--- +name: Build an HTTP server using Express +--- + +Express and other major Node.js HTTP libraries should work out of the box. Bun implements the [`node:http`](https://nodejs.org/api/http.html) and [`node:https`](https://nodejs.org/api/https.html) modules that these libraries rely on. + +{% callout %} +Refer to the [Runtime > Node.js APIs](/docs/runtime/nodejs-apis#node_http) page for more detailed compatibility information. +{% /callout %} + +```sh +$ bun add express +``` + +--- + +To define a simple HTTP route and start a server with Express: + +```ts#server.ts +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}...`); +}); +``` + +--- + +To start the server on `localhost`: + +```sh +$ bun server.ts +``` diff --git a/docs/guides/ecosystem/hono.md b/docs/guides/ecosystem/hono.md new file mode 100644 index 000000000..f0497da1f --- /dev/null +++ b/docs/guides/ecosystem/hono.md @@ -0,0 +1,39 @@ +--- +name: Build an HTTP server using Hono +--- + +[Hono](https://github.com/honojs/hono) is a lightweight ultrafast web framework designed for the edge. + +```ts +import { Hono } from "hono"; +const app = new Hono(); + +app.get("/", c => c.text("Hono!")); + +export default app; +``` + +--- + +Use `create-hono` to get started with one of Hono's project templates. Select `bun` when prompted for a template. + +```bash +$ bunx create-hono myapp +✔ Which template do you want to use? › bun +cloned honojs/starter#main to /path/to/myapp +✔ Copied project files +$ cd myapp +$ bun install +``` + +--- + +Then start the dev server and visit [localhost:3000](http://localhost:3000). + +```bash +$ bun run dev +``` + +--- + +Refer to Hono's guide on [getting started with Bun](https://hono.dev/getting-started/bun) for more information. diff --git a/docs/guides/ecosystem/mongoose.md b/docs/guides/ecosystem/mongoose.md index c2916ce82..406d2e77e 100644 --- a/docs/guides/ecosystem/mongoose.md +++ b/docs/guides/ecosystem/mongoose.md @@ -1,5 +1,5 @@ --- -name: Use MongoDB and Mongoose +name: Read and write data to MongoDB using Mongoose --- MongoDB and Mongoose work out of the box with Bun. This guide assumes you've already installed MongoDB and are running it as background process/service on your development machine. Follow [this guide](https://www.mongodb.com/docs/manual/installation/) for details. diff --git a/docs/guides/ecosystem/prisma.md b/docs/guides/ecosystem/prisma.md index 39627b806..82e79ec06 100644 --- a/docs/guides/ecosystem/prisma.md +++ b/docs/guides/ecosystem/prisma.md @@ -1,5 +1,5 @@ --- -name: Use Prisma +name: Get started using Prisma --- Prisma works our of the box with Bun. First, create a directory and initialize it with `bun init`. diff --git a/docs/guides/ecosystem/react.md b/docs/guides/ecosystem/react.md new file mode 100644 index 000000000..b712e210e --- /dev/null +++ b/docs/guides/ecosystem/react.md @@ -0,0 +1,30 @@ +--- +name: Use React and JSX +--- + +React just works with Bun. Bun supports `.jsx` and `.tsx` files out of the box. Bun's internal transpiler converts JSX syntax into vanilla JavaScript before execution. + +```tsx#react.tsx +function Component(props: {message: string}) { + return ( + <body> + <h1 style={{color: 'red'}}>{props.message}</h1> + </body> + ); +} + +console.log(<Component message="Hello world!" />); +``` + +--- + +Bun implements special logging for JSX to make debugging easier. + +```bash +$ bun run react.tsx +<Component message="Hello world!" /> +``` + +--- + +Refer to [Runtime > JSX](/docs/runtime/jsx) for complete documentation on configuring JSX. diff --git a/docs/guides/ecosystem/ssr-react.md b/docs/guides/ecosystem/ssr-react.md new file mode 100644 index 000000000..59d37db46 --- /dev/null +++ b/docs/guides/ecosystem/ssr-react.md @@ -0,0 +1,42 @@ +--- +name: Server-side render (SSR) a React component +--- + +To render a React component to an HTML stream server-side (SSR): + +```tsx +import { renderToReadableStream } from "react-dom/server"; + +function Component(props: { message: string }) { + return ( + <body> + <h1>{props.message}</h1> + </body> + ); +} + +const stream = await renderToReadableStream( + <Component message="Hello from server!" />, +); +``` + +--- + +Combining this with `Bun.serve()`, we get a simple SSR HTTP server: + +```tsx +Bun.serve({ + async fetch() { + const stream = await renderToReadableStream( + <Component message="Hello from server!" />, + ); + return new Response(stream, { + headers: { "Content-Type": "text/html" }, + }); + }, +}); +``` + +--- + +React `18.3` and later includes an [SSR optimization](https://github.com/facebook/react/pull/25597) that takes advantage of Bun's "direct" `ReadableStream` implementation. diff --git a/docs/guides/ecosystem/stric.md b/docs/guides/ecosystem/stric.md new file mode 100644 index 000000000..309a85709 --- /dev/null +++ b/docs/guides/ecosystem/stric.md @@ -0,0 +1,45 @@ +--- +name: Build an HTTP server using StricJS +--- + +[StricJS](https://github.com/bunsvr) is a minimalist, fast web framework for Bun. Use `bun init` to create an empty project. + +```bash +$ mkdir myapp +$ cd myapp +$ bun init +$ bun add @stricjs/router +``` + +--- + +To implement a simple HTTP server with StricJS: + +```ts#index.ts +import { Router } from '@stricjs/router'; + +export default new Router() + .get('/', () => new Response('Hi')); +``` + +--- + +To serve static files from `/public/*`: + +```ts#index.ts +export default new Router() + .get('/', () => new Response('Hi')) + .get('/public/*', stream('.')); +``` + +--- + +Run the file in watch mode to start the development server. + +```bash +$ bun --watch run index.ts +``` + +--- + +For more info, see Stric's [documentation](https://stricjs.gitbook.io/docs). diff --git a/docs/guides/ecosystem/vite.md b/docs/guides/ecosystem/vite.md index cee5e6013..62c116e02 100644 --- a/docs/guides/ecosystem/vite.md +++ b/docs/guides/ecosystem/vite.md @@ -1,5 +1,5 @@ --- -name: Use Vite +name: Build a frontend using Vite --- {% callout %} diff --git a/docs/guides/http/fetch.md b/docs/guides/http/fetch.md new file mode 100644 index 000000000..7b1c0fb8d --- /dev/null +++ b/docs/guides/http/fetch.md @@ -0,0 +1,24 @@ +--- +name: Send an HTTP request using fetch +--- + +Bun implements the Web-standard [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API for sending HTTP requests. To send a simple `GET` request to a URL: + +```ts +const response = await fetch("https://bun.sh"); +const html = await response.text(); // HTML string +``` + +--- + +To send a `POST` request to an API endpoint. + +```ts +const response = await fetch("https://bun.sh/api", { + method: "POST", + body: JSON.stringify({ message: "Hello from Bun!" }), + headers: { "Content-Type": "application/json" }, +}); + +const body = await response.json(); +``` diff --git a/docs/guides/http/file-uploads.md b/docs/guides/http/file-uploads.md new file mode 100644 index 000000000..a708a238a --- /dev/null +++ b/docs/guides/http/file-uploads.md @@ -0,0 +1,94 @@ +--- +name: Upload files via HTTP using FormData +--- + +To upload files via HTTP with Bun, use the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) API. Let's start with a HTTP server that serves a simple HTML web form. + +```ts#index.ts +const server = Bun.serve({ + port: 4000, + async fetch(req) { + const url = new URL(req.url); + + // return index.html for root path + if (url.pathname === "/") + return new Response(Bun.file("index.html"), { + headers: { + "Content-Type": "text/html", + }, + }); + + return new Response("Not Found", { status: 404 }); + }, +}); + +console.log(`Listening on http://localhost:${server.port}`); +``` + +--- + +We can define our HTML form in another file, `index.html`. + +```html#index.html +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8" /> + <title>Form</title> + </head> + <body> + <form action="/action" method="post" enctype="multipart/form-data"> + <input type="text" name="name" placeholder="Name" /> + <input type="file" name="profilePicture" /> + <input type="submit" value="Submit" /> + </form> + </body> +</html> +``` + +--- + +At this point, we can run the server and visit [`localhost:4000`](http://localhost:4000) to see our form. + +```bash +$ bun run index.ts +Listening on http://localhost:4000 +``` + +--- + +Our form will send a `POST` request to the `/action` endpoint with the form data. Let's handle that request in our server. + +First we use the [`.formData()`](https://developer.mozilla.org/en-US/docs/Web/API/Request/formData) method on the incoming `Request` to asynchonously parse its contents to a `FormData` instance. Then we can use the [`.get()`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/get) method to extract the value of the `name` and `profilePicture` fields. Here `name` corresponds to a `string` and `profilePicture` is a `Blob`. + +Finally, we write the `Blob` to disk using [`Bun.write()`](/docs/api/file-io#writing-files-bun-write). + +```ts-diff#index.ts +const server = Bun.serve({ + port: 4000, + async fetch(req) { + const url = new URL(req.url); + + // return index.html for root path + if (url.pathname === "/") + return new Response(Bun.file("index.html"), { + headers: { + "Content-Type": "text/html", + }, + }); + ++ // parse formdata at /action ++ if (url.pathname === '/action') { ++ const formdata = await req.formData(); ++ const name = formdata.get('name'); ++ const profilePicture = formdata.get('profilePicture');+ ++ if (!profilePicture) throw new Error('Must upload a profile picture.'); ++ // write profilePicture to disk ++ await Bun.write('profilePicture.png', profilePicture); ++ return new Response("Success"); ++ } + + return new Response("Not Found", { status: 404 }); + }, +}); +``` diff --git a/docs/guides/install/add-dev.md b/docs/guides/install/add-dev.md new file mode 100644 index 000000000..833f8cfa2 --- /dev/null +++ b/docs/guides/install/add-dev.md @@ -0,0 +1,26 @@ +--- +name: Add a development dependency +--- + +To add an npm package as a development dependency, use `bun add --development`. + +```sh +$ bun add zod --development +$ bun add zod -d # shorthand +``` + +--- + +This will add the package to `devDependencies` in `package.json`. + +```json-diff +{ + "devDependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-git.md b/docs/guides/install/add-git.md new file mode 100644 index 000000000..c98bc29a8 --- /dev/null +++ b/docs/guides/install/add-git.md @@ -0,0 +1,36 @@ +--- +name: Add a Git dependency +--- + +Bun supports directly adding GitHub repositories as dependencies of your project. + +```sh +$ bun add github:lodash/lodash +``` + +--- + +This will add the following line to your `package.json`: + +```json-diff#package.json +{ + "dependencies": { ++ "lodash": "github:lodash/lodash" + } +} +``` + +--- + +Bun supports a number of protocols for specifying Git dependencies. + +```sh +$ bun add git+https://github.com/lodash/lodash.git +$ bun add git+ssh://github.com/lodash/lodash.git#4.17.21 +$ bun add git@github.com:lodash/lodash.git +$ bun add github:colinhacks/zod +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-optional.md b/docs/guides/install/add-optional.md new file mode 100644 index 000000000..6d02c23e2 --- /dev/null +++ b/docs/guides/install/add-optional.md @@ -0,0 +1,25 @@ +--- +name: Add an optional dependency +--- + +To add an npm package as a peer dependency, use the `--optional` flag. + +```sh +$ bun add zod --optional +``` + +--- + +This will add the package to `optionalDependencies` in `package.json`. + +```json-diff +{ + "optionalDependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-peer.md b/docs/guides/install/add-peer.md new file mode 100644 index 000000000..78d5c86b3 --- /dev/null +++ b/docs/guides/install/add-peer.md @@ -0,0 +1,17 @@ +--- +name: Add a peer dependency +--- + +To add an npm package as a peer dependency, directly modify the `peerDependencies` object in your package.json. Running `bun install` will not install peer dependencies. + +```json-diff +{ + "peerDependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-tarball.md b/docs/guides/install/add-tarball.md new file mode 100644 index 000000000..f09dbbbfa --- /dev/null +++ b/docs/guides/install/add-tarball.md @@ -0,0 +1,33 @@ +--- +name: Add a tarball dependency +--- + +Bun's package manager can install any publicly available tarball URL as a dependency of your project. + +```sh +$ bun add zod@https://registry.npmjs.org/zod/-/zod-3.21.4.tgz +``` + +--- + +Running this command will download, extract, and install the tarball to your project's `node_modules` directory. It will also add the following line to your `package.json`: + +```json-diff#package.json +{ + "dependencies": { ++ "zod": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz" + } +} +``` + +--- + +The package `"zod"` can now be imported as usual. + +```ts +import { z } from "zod"; +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add.md b/docs/guides/install/add.md new file mode 100644 index 000000000..dfb88e5e4 --- /dev/null +++ b/docs/guides/install/add.md @@ -0,0 +1,42 @@ +--- +name: Add a dependency +--- + +To add an npm package as a dependency, use `bun add`. + +```sh +$ bun add zod +``` + +--- + +This will add the package to `dependencies` in `package.json`. By default, the `^` range specifier will be used, to indicate that any future minor or patch versions are acceptable. + +```json-diff +{ + "dependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +To "pin" to the `latest` version of the package, use `--exact`. This will add the package to `dependencies` without the `^`, pinning your project to the exact version you installed. + +```sh +$ bun add zod --exact +``` + +--- + +To specify an exact version or a tag: + +```sh +$ bun add zod@3.0.0 +$ bun add zod@next +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/cicd.md b/docs/guides/install/cicd.md new file mode 100644 index 000000000..4be29925d --- /dev/null +++ b/docs/guides/install/cicd.md @@ -0,0 +1,41 @@ +--- +name: Install dependencies with Bun in GitHub Actions +--- + +Use the official [`setup-bun`](https://github.com/oven-sh/setup-bun) GitHub Action to install `bun` in your GitHub Actions runner. + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: actions/checkout@v3 ++ - uses: oven-sh/setup-bun@v1 + + # run any `bun` or `bunx` command ++ - run: bun install +``` + +--- + +To specify a version of Bun to install: + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: oven-sh/setup-bun@v1 ++ with: ++ version: 0.7.0 # or "canary" +``` + +--- + +Refer to the [README.md](https://github.com/oven-sh/setup-bun) for complete documentation of the `setup-bun` GitHub Action. diff --git a/docs/guides/install/custom-registry.md b/docs/guides/install/custom-registry.md new file mode 100644 index 000000000..64b3cf76b --- /dev/null +++ b/docs/guides/install/custom-registry.md @@ -0,0 +1,30 @@ +--- +name: Override the default npm registry for bun install +--- + +The default registry is `registry.npmjs.org`. This can be globally configured in `bunfig.toml`. + +```toml#bunfig.toml +[install] +# set default registry as a string +registry = "https://registry.npmjs.org" + +# if needed, set a token +registry = { url = "https://registry.npmjs.org", token = "123456" } + +# if needed, set a username/password +registry = "https://username:password@registry.npmjs.org" +``` + +--- + +Your `bunfig.toml` can reference environment variables. Bun automatically loads environment variables from `.env.local`, `.env.[NODE_ENV]`, and `.env`. See [Docs > Environment variables](/docs/cli/run#environment-variables) for more information. + +```toml#bunfig.toml +[install] +registry = { url = "https://registry.npmjs.org", token = "$npm_token" } +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/index.json b/docs/guides/install/index.json new file mode 100644 index 000000000..017ef2845 --- /dev/null +++ b/docs/guides/install/index.json @@ -0,0 +1,4 @@ +{ + "name": "Package manager", + "description": "A collection of guides for managing dependencies with Bun's package manager" +} diff --git a/docs/guides/install/npm-alias.md b/docs/guides/install/npm-alias.md new file mode 100644 index 000000000..0b38d8c71 --- /dev/null +++ b/docs/guides/install/npm-alias.md @@ -0,0 +1,23 @@ +--- +name: Install a package under a different name +--- + +To install an npm package under an alias: + +```sh +$ bun add my-custom-name@npm:zod +``` + +--- + +The `zod` package can now be imported as `my-custom-name`. + +```ts +import { z } from "my-custom-name"; + +z.string(); +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/registry-scope.md b/docs/guides/install/registry-scope.md new file mode 100644 index 000000000..48f7dee79 --- /dev/null +++ b/docs/guides/install/registry-scope.md @@ -0,0 +1,32 @@ +--- +name: Configure a private registry for an organization scope with bun install +--- + +Bun does not read `.npmrc` files; instead private registries are configured via `bunfig.toml`. To configure a registry for a particular npm scope: + +```toml#bunfig.toml +[install.scopes] +# as a string +"@myorg1" = "https://username:password@registry.myorg.com/" + +# as an object with username/password +# you can reference environment variables +"@myorg2" = { username = "myusername", password = "$npm_pass", url = "https://registry.myorg.com/" } + +# as an object with token +"@myorg3" = { token = "$npm_token", url = "https://registry.myorg.com/" } + +``` + +--- + +Your `bunfig.toml` can reference environment variables. Bun automatically loads environment variables from `.env.local`, `.env.[NODE_ENV]`, and `.env`. See [Docs > Environment variables](/docs/cli/run#environment-variables) for more information. + +```toml#bunfig.toml +[install.scopes] +"@myorg3" = { token = "$npm_token", url = "https://registry.myorg.com/" } +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/read-file/json.md b/docs/guides/read-file/json.md index 3b7488472..e14fd560a 100644 --- a/docs/guides/read-file/json.md +++ b/docs/guides/read-file/json.md @@ -4,31 +4,14 @@ name: Read a JSON file The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob` and allows you to lazily read the file in a variety of formats. Use `.json()` to read and parse the contents of a `.json` file as a plain object. +The MIME type of the `BunFile` will be set accordingly. + ```ts const path = "/path/to/package.json"; const file = Bun.file(path); const contents = await file.json(); // { name: "my-package" } -``` - ---- - -The MIME type of the `BunFile` will be set accordingly. - -```ts -const path = "/path/to/package.json"; -const file = Bun.file(path); file.type; // => "application/json;charset=utf-8"; ``` - ---- - -If the path to the `.json` file is static, it can be directly imported as a module. - -```ts -import pkg from "./package.json"; - -pkg.name; // => "my-package" -``` diff --git a/docs/guides/runtime/cicd.md b/docs/guides/runtime/cicd.md new file mode 100644 index 000000000..6dfef2ddd --- /dev/null +++ b/docs/guides/runtime/cicd.md @@ -0,0 +1,43 @@ +--- +name: Install and run Bun in GitHub Actions +--- + +Use the official [`setup-bun`](https://github.com/oven-sh/setup-bun) GitHub Action to install `bun` in your GitHub Actions runner. + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: actions/checkout@v3 ++ - uses: oven-sh/setup-bun@v1 + + # run any `bun` or `bunx` command ++ - run: bun install ++ - run: bun index.ts ++ - run: bun run build +``` + +--- + +To specify a version of Bun to install: + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: oven-sh/setup-bun@v1 ++ with: ++ version: 0.7.0 # or "canary" +``` + +--- + +Refer to the [README.md](https://github.com/oven-sh/setup-bun) for complete documentation of the `setup-bun` GitHub Action. diff --git a/docs/guides/runtime/import-json.md b/docs/guides/runtime/import-json.md new file mode 100644 index 000000000..3db2daaea --- /dev/null +++ b/docs/guides/runtime/import-json.md @@ -0,0 +1,32 @@ +--- +name: Import a JSON file +--- + +Bun natively supports `.json` imports. + +```json#package.json +{ + "name": "bun", + "version": "1.0.0", + "author": { + "name": "John Dough", + "email": "john@dough.com" + } +} +``` + +--- + +Import the file like any other source file. + +```ts +import data from "./package.json"; + +data.name; // => "bun" +data.version; // => "1.0.0" +data.author.name; // => "John Dough" +``` + +--- + +See [Docs > Runtime > TypeScript](/docs/runtime/typescript) for more information on using TypeScript with Bun. diff --git a/docs/guides/runtime/import-toml.md b/docs/guides/runtime/import-toml.md new file mode 100644 index 000000000..2a2e47aa4 --- /dev/null +++ b/docs/guides/runtime/import-toml.md @@ -0,0 +1,30 @@ +--- +name: Import a TOML file +--- + +Bun natively supports importing `.toml` files. + +```toml#data.toml +name = "bun" +version = "1.0.0" + +[author] +name = "John Dough" +email = "john@dough.com" +``` + +--- + +Import the file like any other source file. + +```ts +import data from "./data.toml"; + +data.name; // => "bun" +data.version; // => "1.0.0" +data.author.name; // => "John Dough" +``` + +--- + +See [Docs > Runtime > TypeScript](/docs/runtime/typescript) for more information on using TypeScript with Bun. diff --git a/docs/guides/runtime/index.json b/docs/guides/runtime/index.json new file mode 100644 index 000000000..fad27c69d --- /dev/null +++ b/docs/guides/runtime/index.json @@ -0,0 +1,4 @@ +{ + "name": "Runtime", + "description": "A collection of guides for executing code with the Bun runtime" +} diff --git a/docs/guides/runtime/tsconfig-paths.md b/docs/guides/runtime/tsconfig-paths.md new file mode 100644 index 000000000..5c3f591f5 --- /dev/null +++ b/docs/guides/runtime/tsconfig-paths.md @@ -0,0 +1,29 @@ +--- +name: Re-map import paths +--- + +Bun reads the `paths` field in your `tsconfig.json` to re-write import paths. This is useful for aliasing package names or avoiding long relative paths. + +```json +{ + "compilerOptions": { + "paths": { + "my-custom-name": "zod", + "@components/*": "./src/components/*" + } + } +} +``` + +--- + +With the above `tsconfig.json`, the following imports will be re-written: + +```ts +import { z } from "my-custom-name"; // imports from "zod" +import { Button } from "@components/Button"; // imports from "./src/components/Button" +``` + +--- + +See [Docs > Runtime > TypeScript](/docs/runtime/typescript) for more information on using TypeScript with Bun. diff --git a/docs/guides/util/hash-a-password.md b/docs/guides/util/hash-a-password.md new file mode 100644 index 000000000..6941bfcfe --- /dev/null +++ b/docs/guides/util/hash-a-password.md @@ -0,0 +1,54 @@ +--- +name: Hash a password +--- + +The `Bun.password.hash()` function provides a fast, built-in mechanism for securely hashing passwords in Bun. No third-party dependencies are required. + +```ts +const password = "super-secure-pa$$word"; + +const hash = await Bun.password.hash(password); +// => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh6E8DQRhEXg/M/SqYCNu6gVdRRNs$GzJ8PuBi+K+BVojzPfS5mjnC8OpLGtv8KJqF99eP6a4 +``` + +--- + +By default this uses the [Argon2id](https://en.wikipedia.org/wiki/Argon2) algorithm. Pass a second argument to `Bun.hash.password()` to use a different algorithm or configure the hashing parameters. + +```ts +const password = "super-secure-pa$$word"; + +// use argon2 (default) +const argonHash = await Bun.password.hash(password, { + memoryCost: 4, // memory usage in kibibytes + timeCost: 3, // the number of iterations +}); +``` + +--- + +Bun also implements the [bcrypt](https://en.wikipedia.org/wiki/Bcrypt) algorithm. Specify `algorithm: "bcrypt"` to use it. + +```ts +// use bcrypt +const bcryptHash = await Bun.password.hash(password, { + algorithm: "bcrypt", + cost: 4, // number between 4-31 +}); +``` + +--- + +To verify a password, use `Bun.password.verify()`. The algorithm and its parameters are stored in the hash itself, so there's no need to re-specify any configuration. + +```ts +const password = "super-secure-pa$$word"; +const hash = await Bun.password.hash(password); + +const isMatch = await Bun.password.verify(password, hash); +// => true +``` + +--- + +See [Docs > API > Hashing](/docs/api/hashing#bun-password) for complete documentation. diff --git a/docs/guides/write-file/unlink.md b/docs/guides/write-file/unlink.md new file mode 100644 index 000000000..ba0cbe8b1 --- /dev/null +++ b/docs/guides/write-file/unlink.md @@ -0,0 +1,23 @@ +--- +name: Delete a file +--- + +To synchronously delete a file with Bun, use the `unlinkSync` function from the [`node:fs`](https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback) module. (Currently, there is no `Bun` API for deleting files.) + +```ts +import { unlinkSync } from "node:fs"; + +const path = "/path/to/file.txt"; +unlinkSync(path); +``` + +--- + +To remove a file asynchronously, use the `unlink` function from the [`node:fs/promises`](https://nodejs.org/api/fs.html#fs_fspromises_unlink_path) module. + +```ts +import { unlink } from "node:fs/promises"; + +const path = "/path/to/file.txt"; +await unlink(path); +``` |