bun v0.0.76
To upgrade:
bun upgradeWhat's new
- Type definitions for better editor integration and TypeScript LSP! There are types for the runtime APIs now in the
bun-typesnpm package. A PR for @types/bun is waiting review (feel free to nudge them). Bun.serve()is a fast HTTP & HTTPS server that supports theRequestandResponseWeb APIs. The server is a fork of uWebSocketsBun.write()– one API for writing files, pipes, and copying files leveraging the fastest system calls available for the input & platform. It uses theBlobWeb API.Bun.mmap(path)lets you read files as a live-updatingUint8Arrayvia the mmap(2) syscall. Thank you @evanwashere!!Bun.hash(bufferOrString)exposes fast non-cryptographic hashing functions. Useful for things likeETag, not for passwords.Bun.allocUnsafe(length)creates a new Uint8Array ~3.5x faster than new Uint8Array, but it is not zero-initialized. This is similar to Node'sBuffer.allocUnsafe, though without the memory pool currently- Several web APIs have been added, including
URL - A few more examples have been added to the
examplesfolder - Bug fixes to
fs.read()andfs.write()and some more tests for fs Response.redirect(),Response.json(), andResponse.error()have been addedimport.meta.urlis now a file:// url stringBun.resolveandBun.resolveSynclet you resolve the same asimportdoes. It throws aResolveErroron failure (same asimport)Bun.stderrandBun.stdoutnow return aBlobSharedArrayBufferis now enabled (thanks @evanwashere!)- Updated Next.js version
New Web APIs in bun.js
Going forward, Bun will first try to rely on WebKit/Safari's implementations of Web APIs rather than writing new ones. This will improve Web API compatibility while reducing bun's scope, without compromising performance
These Web APIs are now available in bun.js and powered by Safari's implementation:
URLURLSearchParamsErrorEventEventEventTargetDOMExceptionHeadersuses WebKit's implementation now instead of a custom oneAbortSignal(not wired up to fetch or fs yet, it exists but not very useful)AbortController
Also added:
reportError(does not dispatch an"error"event yet)
Additionally, all the builtin constructors in bun now have a .prototype property (this was missing before)
Bun.serve - fast HTTP server
For a hello world HTTP server that writes "bun!", Bun.serve serves about 2.5x more requests per second than node.js on Linux:
| Requests per second | Runtime |
|---|---|
| ~64,000 | Node 16 |
| ~160,000 | Bun |
Bigger is better
Code
Bun:
Bun.serve({
fetch(req: Request) {
return new Response(`bun!`);
},
port: 3000,
});Node:
require("http")
.createServer((req, res) => res.end("bun!"))
.listen(8080);
Usage
Two ways to start an HTTP server with bun.js:
export defaultan object with afetchfunction
If the file used to start bun has a default export with a fetch function, it will start the http server.
// hi.js
export default {
fetch(req) {
return new Response("HI!");
},
};
// bun ./hi.jsfetch receives a Request object and must return either a Response or a Promise<Response>. In a future version, it might have an additional arguments for things like cookies.
Bun.servestarts the http server explicitly
Bun.serve({
fetch(req) {
return new Response("HI!");
},
});Error handling
For error handling, you get an error function.
If development: true and error is not defined or doesn't return a Response, you will get an exception page with a stack trace:
It will hopefully make it easier to debug issues with bun until bun gets debugger support. This error page is based on what bun dev does.
If the error function returns a Response, it will be served instead
Bun.serve({
fetch(req) {
throw new Error("woops!");
},
error(error: Error) {
return new Response("Uh oh!!\n" + error.toString(), { status: 500 });
},
});If the error function itself throws and development is false, a generic 500 page will be shown
Currently, there is no way to stop the HTTP server once started 😅, but that will be added in a future version.
The interface for Bun.serve is based on what Cloudflare Workers does.
Bun.write() – optimizing I/O
Bun.write lets you write, copy or pipe files automatically using the fastest system calls compatible with the input and platform.
interface Bun {
write(
destination: string | number | FileBlob,
input: string | FileBlob | Blob | ArrayBufferView
): Promise<number>;
}| Output | Input | System Call | Platform |
|---|---|---|---|
| file | file | copy_file_range | Linux |
| file | pipe | sendfile | Linux |
| pipe | pipe | splice | Linux |
| terminal | file | sendfile | Linux |
| terminal | terminal | sendfile | Linux |
| socket | file or pipe | sendfile (if http, not https) | Linux |
| file (path, doesn't exist) | file (path) | clonefile | macOS |
| file | file | fcopyfile | macOS |
| file | Blob or string | write | macOS |
| file | Blob or string | write | Linux |
All this complexity is handled by a single function.
// Write "Hello World" to output.txt
await Bun.write("output.txt", "Hello World");// log a file to stdout
await Bun.write(Bun.stdout, Bun.file("input.txt"));// write the HTTP response body to disk
await Bun.write("index.html", await fetch("http://example.com"));
// this does the same thing
await Bun.write(Bun.file("index.html"), await fetch("http://example.com"));// copy input.txt to output.txt
await Bun.write("output.txt", Bun.file("input.txt"));Bug fixes
- Fixed a bug on Linux where sometimes the HTTP thread would incorrectly go to sleep, causing requests to hang forever 😢 . Previously, it relied on data in the queues to determine whether it should idle and now it increments a counter.
- Fixed a bug that sometimes caused
requireto produce incorrect output depending on how the module was used - Fixed a number of crashes in
bun devrelated to HMR & websockets - Jarred-Sumner/bun@daeede2 fs.openSyncnow supportsmodeandflags- Jarred-Sumner/bun@c73fcb0fs.readandfs.writewere incorrectly returning the output offs/promisesversions, this is fixed- Fixed a crash that could occur during garbage collection when an
fsfunction received a TypedArray as input. - Jarred-Sumner/bun@614f64b. This also improves performance of sending array buffers to native a little Response's constructor previously readstatusCodeinstead ofstatus. This was incorrect and has been fixed.- Fixed a bug where
fs.statreported incorrect information on macOS x64 - Slight improvement to HMR reliability if reading large files or slow filesystems over websockets - 89cd35f
- Fixed a potential infinite loop when generating a sourcemap - fe973a5
improve performance of accessingBun.TranspilerandBun.unsafe29a759a
