aboutsummaryrefslogtreecommitdiff
path: root/docs/api
diff options
context:
space:
mode:
Diffstat (limited to 'docs/api')
-rw-r--r--docs/api/binary-data.md10
-rw-r--r--docs/api/file-io.md2
-rw-r--r--docs/api/file-system-router.md1
-rw-r--r--docs/api/http.md6
-rw-r--r--docs/api/import-meta.md2
-rw-r--r--docs/api/spawn.md54
-rw-r--r--docs/api/sqlite.md14
-rw-r--r--docs/api/transpiler.md2
-rw-r--r--docs/api/utils.md4
-rw-r--r--docs/api/websockets.md17
-rw-r--r--docs/api/workers.md21
11 files changed, 110 insertions, 23 deletions
diff --git a/docs/api/binary-data.md b/docs/api/binary-data.md
index a75d08309..91b314b98 100644
--- a/docs/api/binary-data.md
+++ b/docs/api/binary-data.md
@@ -26,10 +26,10 @@ Below is a quick "cheat sheet" that doubles as a table of contents. Click an ite
---
-<!-- - [`File`](#file)
-- _Browser only_. A subclass of `Blob` that represents a file. Has a `name` and `lastModified` timestamp. There is experimental support in Node.js v20; Bun does not support `File` yet; most of its functionality is provided by `BunFile`.
+- [`File`](#file)
+- A subclass of `Blob` that represents a file. Has a `name` and `lastModified` timestamp. There is experimental support in Node.js v20.
---- -->
+---
- [`BunFile`](#bunfile)
- _Bun only_. A subclass of `Blob` that represents a lazily-loaded file on disk. Created with `Bun.file(path)`.
@@ -412,7 +412,7 @@ For complete documentation, refer to the [Node.js documentation](https://nodejs.
`Blob` is a Web API commonly used for representing files. `Blob` was initially implemented in browsers (unlike `ArrayBuffer` which is part of JavaScript itself), but it is now supported in Node and Bun.
-It isn't common to directly create `Blob` instances. More often, you'll recieve instances of `Blob` from an external source (like an `<input type="file">` element in the browser) or library. That said, it is possible to create a `Blob` from one or more string or binary "blob parts".
+It isn't common to directly create `Blob` instances. More often, you'll receive instances of `Blob` from an external source (like an `<input type="file">` element in the browser) or library. That said, it is possible to create a `Blob` from one or more string or binary "blob parts".
```ts
const blob = new Blob(["<html>Hello</html>"], {
@@ -507,7 +507,7 @@ for await (const chunk of stream) {
}
```
-For a more complete discusson of streams in Bun, see [API > Streams](/docs/api/streams).
+For a more complete discussion of streams in Bun, see [API > Streams](/docs/api/streams).
## Conversion
diff --git a/docs/api/file-io.md b/docs/api/file-io.md
index e6902cc6a..f37473c33 100644
--- a/docs/api/file-io.md
+++ b/docs/api/file-io.md
@@ -2,7 +2,7 @@
<!-- **Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. Existing Node.js projects may use Bun's [nearly complete](/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module. -->
-**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir`, you can use Bun's [nearly complete](/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module.
+**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir` or `readdir`, you can use Bun's [nearly complete](/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module.
{% /callout %}
diff --git a/docs/api/file-system-router.md b/docs/api/file-system-router.md
index 964652401..8e1fbe0fc 100644
--- a/docs/api/file-system-router.md
+++ b/docs/api/file-system-router.md
@@ -93,6 +93,7 @@ interface Bun {
style: "nextjs";
origin?: string;
assetPrefix?: string;
+ fileExtensions?: string[];
});
reload(): void;
diff --git a/docs/api/http.md b/docs/api/http.md
index 629570335..3f476feb2 100644
--- a/docs/api/http.md
+++ b/docs/api/http.md
@@ -71,7 +71,7 @@ In development mode, Bun will surface errors in-browser with a built-in error pa
{% image src="/images/exception_page.png" caption="Bun's built-in 500 page" /%}
-To handle server-side errors, implement an `error` handler. This function should return a `Response` to served to the client when an error occurs. This response will supercede Bun's default error page in `development` mode.
+To handle server-side errors, implement an `error` handler. This function should return a `Response` to serve to the client when an error occurs. This response will supersede Bun's default error page in `development` mode.
```ts
Bun.serve({
@@ -212,9 +212,7 @@ $ bun --hot server.ts
To stream a file, return a `Response` object with a `BunFile` object as the body.
```ts
-import { serve, file } from "bun";
-
-serve({
+Bun.serve({
fetch(req) {
return new Response(Bun.file("./hello.txt"));
},
diff --git a/docs/api/import-meta.md b/docs/api/import-meta.md
index 3c22308ce..37f35884d 100644
--- a/docs/api/import-meta.md
+++ b/docs/api/import-meta.md
@@ -39,7 +39,7 @@ import.meta.resolveSync("zod")
---
- `import.meta.resolve{Sync}`
-- Resolve a module specifier (e.g. `"zod"` or `"./file.tsx`) to an absolute path. While file would be imported if the specifier were imported from this file?
+- Resolve a module specifier (e.g. `"zod"` or `"./file.tsx"`) to an absolute path. While file would be imported if the specifier were imported from this file?
```ts
import.meta.resolveSync("zod");
diff --git a/docs/api/spawn.md b/docs/api/spawn.md
index a85f9d08c..644f8cee3 100644
--- a/docs/api/spawn.md
+++ b/docs/api/spawn.md
@@ -183,6 +183,60 @@ const proc = Bun.spawn(["echo", "hello"]);
proc.unref();
```
+## Inter-process communication (IPC)
+
+Bun supports direct inter-process communication channel between two `bun` processes. To receive messages from a spawned Bun subprocess, specify an `ipc` handler.
+{%callout%}
+**Note** — This API is only compatible with other `bun` processes. Use `process.execPath` to get a path to the currently running `bun` executable.
+{%/callout%}
+
+```ts#parent.ts
+const child = Bun.spawn(["bun", "child.ts"], {
+ ipc(message) {
+ /**
+ * The message received from the sub process
+ **/
+ },
+});
+```
+
+The parent process can send messages to the subprocess using the `.send()` method on the returned `Subprocess` instance. A reference to the sending subprocess is also available as the second argument in the `ipc` handler.
+
+```ts#parent.ts
+const childProc = Bun.spawn(["bun", "child.ts"], {
+ ipc(message, childProc) {
+ /**
+ * The message received from the sub process
+ **/
+ childProc.send("Respond to child")
+ },
+});
+
+childProc.send("I am your father"); // The parent can send messages to the child as well
+```
+
+Meanwhile the child process can send messages to its parent using with `process.send()` and receive messages with `process.on("message")`. This is the same API used for `child_process.fork()` in Node.js.
+
+```ts#child.ts
+process.send("Hello from child as string");
+process.send({ message: "Hello from child as object" });
+
+process.on("message", (message) => {
+ // print message from parent
+ console.log(message);
+});
+```
+
+All messages are serialized using the JSC `serialize` API, which allows for the same set of [transferrable types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) supported by `postMessage` and `structuredClone`, including strings, typed arrays, streams, and objects.
+
+```ts#child.ts
+// send a string
+process.send("Hello from child as string");
+
+// send an object
+process.send({ message: "Hello from child as object" });
+```
+
## Blocking API (`Bun.spawnSync()`)
Bun provides a synchronous equivalent of `Bun.spawn` called `Bun.spawnSync`. This is a blocking API that supports the same inputs and parameters as `Bun.spawn`. It returns a `SyncSubprocess` object, which differs from `Subprocess` in a few ways.
diff --git a/docs/api/sqlite.md b/docs/api/sqlite.md
index e04b8ded7..3749fb8b4 100644
--- a/docs/api/sqlite.md
+++ b/docs/api/sqlite.md
@@ -99,6 +99,20 @@ const query = db.prepare("SELECT * FROM foo WHERE bar = ?");
{% /callout %}
+## WAL mode
+
+SQLite supports [write-ahead log mode](https://www.sqlite.org/wal.html) (WAL) which dramatically improves performance, especially in situations with many concurrent writes. It's broadly recommended to enable WAL mode for most typical applications.
+
+To enable WAL mode, run this pragma query at the beginning of your application:
+
+```ts
+db.exec("PRAGMA journal_mode = WAL;");
+```
+
+{% details summary="What is WAL mode" %}
+In WAL mode, writes to the database are written directly to a separate file called the "WAL file" (write-ahead log). This file will be later integrated into the main database file. Think of it as a buffer for pending writes. Refer to the [SQLite docs](https://www.sqlite.org/wal.html) for a more detailed overview.
+{% /details %}
+
## Statements
A `Statement` is a _prepared query_, which means it's been parsed and compiled into an efficient binary form. It can be executed multiple times in a performant way.
diff --git a/docs/api/transpiler.md b/docs/api/transpiler.md
index 6d81a1ef9..ede4ee7cc 100644
--- a/docs/api/transpiler.md
+++ b/docs/api/transpiler.md
@@ -76,7 +76,7 @@ await transpiler.transform("<div>hi!</div>", "tsx");
```
{% details summary="Nitty gritty" %}
-The `.tranform()` method runs the transpiler in Bun's worker threadpool, so if you run it 100 times, it will run it across `Math.floor($cpu_count * 0.8)` threads, without blocking the main JavaScript thread.
+The `.transform()` method runs the transpiler in Bun's worker threadpool, so if you run it 100 times, it will run it across `Math.floor($cpu_count * 0.8)` threads, without blocking the main JavaScript thread.
If your code uses a macro, it will potentially spawn a new copy of Bun's JavaScript runtime environment in that new thread.
{% /details %}
diff --git a/docs/api/utils.md b/docs/api/utils.md
index de2dc6994..9889d6aa0 100644
--- a/docs/api/utils.md
+++ b/docs/api/utils.md
@@ -183,7 +183,7 @@ const currentFile = import.meta.url;
Bun.openInEditor(currentFile);
```
-You can override this via the `debug.editor` setting in your [`bunfig.toml`](/docs/runtime/configuration)
+You can override this via the `debug.editor` setting in your [`bunfig.toml`](/docs/runtime/bunfig)
```toml-diff#bunfig.toml
+ [debug]
@@ -204,7 +204,7 @@ Bun.ArrayBufferSink;
## `Bun.deepEquals()`
-Nestedly checks if two objects are equivalent. This is used internally by `expect().toEqual()` in `bun:test`.
+Recursively checks if two objects are equivalent. This is used internally by `expect().toEqual()` in `bun:test`.
```ts
const foo = { a: 1, b: 2, c: { d: 3 } };
diff --git a/docs/api/websockets.md b/docs/api/websockets.md
index e704419bb..4e55b8761 100644
--- a/docs/api/websockets.md
+++ b/docs/api/websockets.md
@@ -87,7 +87,7 @@ ws.send(new Uint8Array([1, 2, 3])); // TypedArray | DataView
### Headers
-Once the upgrade succeeds, Bun will send a `101 Switching Protocols` response per the [spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism). Additional `headers` can be attched to this `Response` in the call to `server.upgrade()`.
+Once the upgrade succeeds, Bun will send a `101 Switching Protocols` response per the [spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism). Additional `headers` can be attached to this `Response` in the call to `server.upgrade()`.
```ts
Bun.serve({
@@ -161,7 +161,7 @@ socket.addEventListener("message", event => {
### Pub/Sub
-Bun's `ServerWebSocket` implementation implements a native publish-subscribe API for topic-based broadcasting. Individual sockets can `.subscribe()` to a topic (specified with a string identifier) and `.publish()` messages to all other subscribers to that topic. This topic-based broadcast API is similar to [MQTT](https://en.wikipedia.org/wiki/MQTT) and [Redis Pub/Sub](https://redis.io/topics/pubsub).
+Bun's `ServerWebSocket` implementation implements a native publish-subscribe API for topic-based broadcasting. Individual sockets can `.subscribe()` to a topic (specified with a string identifier) and `.publish()` messages to all other subscribers to that topic (excluding itself). This topic-based broadcast API is similar to [MQTT](https://en.wikipedia.org/wiki/MQTT) and [Redis Pub/Sub](https://redis.io/topics/pubsub).
```ts
const server = Bun.serve<{ username: string }>({
@@ -200,7 +200,18 @@ const server = Bun.serve<{ username: string }>({
console.log(`Listening on ${server.hostname}:${server.port}`);
```
-Calling `.publish(data)` will send the message to all subscribers of a topic _except_ the socket that called `.publish()`.
+Calling `.publish(data)` will send the message to all subscribers of a topic _except_ the socket that called `.publish()`. To send a message to all subscribers of a topic, use the `.publish()` method on the `Server` instance.
+
+```ts
+const server = Bun.serve({
+ websocket: {
+ // ...
+ },
+});
+
+// listen for some external event
+server.publish("the-group-chat", "Hello world");
+```
### Compression
diff --git a/docs/api/workers.md b/docs/api/workers.md
index 417b77148..2b8c4fe13 100644
--- a/docs/api/workers.md
+++ b/docs/api/workers.md
@@ -10,7 +10,7 @@ Bun implements a minimal version of the [Web Workers API](https://developer.mozi
Like in browsers, [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) is a global. Use it to create a new worker thread.
-From the main thread:
+### From the main thread
```js#Main_thread
const workerURL = new URL("worker.ts", import.meta.url).href;
@@ -22,16 +22,25 @@ worker.onmessage = event => {
};
```
-Worker thread:
+### Worker thread
```ts#worker.ts_(Worker_thread)
+// prevents TS errors
+declare var self: Worker;
+
self.onmessage = (event: MessageEvent) => {
console.log(event.data);
postMessage("world");
};
```
-You can use `import`/`export` syntax in your worker code. Unlike in browsers, there's no need to specify `{type: "module"}` to use ES Modules.
+To prevent TypeScript errors when using `self`, add this line to the top of your worker file.
+
+```ts
+declare var self: Worker;
+```
+
+You can use `import` and `export` syntax in your worker code. Unlike in browsers, there's no need to specify `{type: "module"}` to use ES Modules.
To simplify error handling, the initial script to load is resolved at the time `new Worker(url)` is called.
@@ -123,14 +132,14 @@ By default, an active `Worker` will keep the main (spawning) process alive, so a
### `worker.unref()`
-To stop a running worker from keeping the process alive, call `worker.unref()`. This decouples the lifetime of the worker to the lifetime of the main process, and is equivlent to what Node.js' `worker_threads` does.
+To stop a running worker from keeping the process alive, call `worker.unref()`. This decouples the lifetime of the worker to the lifetime of the main process, and is equivalent to what Node.js' `worker_threads` does.
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
worker.unref();
```
-Note: `worker.unref()` is not available in browers.
+Note: `worker.unref()` is not available in browsers.
### `worker.ref()`
@@ -151,7 +160,7 @@ const worker = new Worker(new URL("worker.ts", import.meta.url).href, {
});
```
-Note: `worker.ref()` is not available in browers.
+Note: `worker.ref()` is not available in browsers.
## Memory usage with `smol`