Migrating from Bun to Nub
Move a Bun project onto Node and Nub, from running files and scripts to env files, with a map of every Bun-specific API to its Node or npm replacement.
Nub runs your TypeScript directly on the Node your project pins, and your package manager and lockfile stay where they are. Most of a migration is replacing the Bun.* APIs your code calls, which have no direct Node counterpart.
bun run src/index.ts # before
nub src/index.ts # afterRunning files
Nub runs TypeScript and JSX on stock Node, including enums, namespaces, parameter properties, and emitDecoratorMetadata. There is no build step and no loader to register.
The file runner is nub <file>, and nub run <script> runs a package.json script. There is no nub run <file> form:
nub src/server.ts # runs the file
nub run dev # runs the "dev" scriptChoosing a Node version
Bun bundles its own runtime; Nub runs the Node your project pins and provisions it on demand. Pin it with .node-version, .nvmrc, devEngines.runtime, or nub node pin:
nub node pin 27 # writes the pinPick a version your dependencies support. A package that needs a newer Node API fails at runtime on an older Node, not at install. A current LTS or the latest release is the safe choice; see Managing Node versions.
Package manager and lockfile
Nub's package-manager commands follow pnpm's grammar:
bun install # → nub install (alias: nub i)
bun add <pkg> # → nub add <pkg>
bun remove <pkg> # → nub remove <pkg>
bunx <pkg> # → nubx <pkg> (fetch: nub dlx <pkg>)Nub round-trips your existing bun.lock, so the lockfile needs no conversion. It also reads the bunfig.toml install settings that map onto Nub's; see Bun projects.
Scripts: parallel and sequential
Bun's bun run --parallel and --sequential take a list of script names. Nub follows pnpm's grammar instead, where nub run a b runs script a with b as its argument.
To run several scripts, match their names with a /regex/ selector. The matched scripts run concurrently:
nub run "/^(lint|typecheck|test)$/" # three named scripts
nub run "/^check:/" # every check:* script
nub run --workspace-concurrency 1 "/^build:/" # one at a timeSee multiple scripts. The run-p and run-s commands from npm-run-all2 also work under Nub.
Environment files
Nub loads your .env* files automatically for file runs, nub run, and nub watch. Like Bun, it accepts --env-file, and an explicit file turns off automatic discovery for that run:
bun --env-file=.env.production src/index.ts
nub --env-file=.env.production src/index.tsOne difference: Nub expands ${VAR} references only in the automatic .env* files. A file named with --env-file loads verbatim, as on Node, while Bun expands it. To keep expansion, load the file another way:
envFileinnub.jsonc— explicit and expanded, but loads on every run, and every listed file must exist.- A mode —
APP_ENV=production nub src/index.tsexpands, but loads the full cascade, so a.env.localvalue outranks.env.production.
The shell environment still wins over any file. See Environment variables.
Shell commands: Bun.$
The closest Node counterpart to Bun's $ is dax. It has the same tagged-template shape, the same chainable output methods, and the same escaping of interpolated values, so most call sites change only their import:
// before (Bun)
import { $ } from "bun";
const out = await $`ls -la ${dir}`.text();// after (Node) — dax
import { $ } from "dax";
const out = await $`ls -la ${dir}`.text();The dax package runs a real shell language, with pipes, redirects, globs, and &&, and ships common commands such as cat, cp, and rm so pipelines run on Windows too. A pipeline like $`cat file.txt | grep foo` carries over unchanged.
zx is the more widely used $ library. For a call that runs one program with an argument array rather than a shell line, execa is closer to Bun.spawn.
Database access: Bun.sql
Bun's Postgres client, Bun.sql, is modeled on postgres.js, so that package is the nearest swap. Construct the client yourself and close it on shutdown:
import postgres from "postgres";
const sql = postgres(process.env.DATABASE_URL!);
const rows = await sql`select * from users where id = ${id}`;
await sql.end();If the project already uses Prisma, whose driver adapters pull in pg, use pg for raw queries instead of adding a second client:
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const sql = "select * from users where id = $1";
const { rows } = await pool.query(sql, [id]);import.meta and CommonJS globals
These are direct renames in ESM:
| Bun | Node (ESM) |
|---|---|
import.meta.dir | import.meta.dirname |
import.meta.file | import.meta.filename |
import.meta.main | import.meta.main (Node 24+) — otherwise compare process.argv[1] to the resolved module path. |
__dirname (in ESM) | import.meta.dirname |
__filename (in ESM) | import.meta.filename |
The full Bun.* and bun:* API map
Standard web APIs such as fetch, WebSocket, Blob, URL, crypto.subtle, and streams exist on Node too, so they need no change. Bun.Transpiler is unnecessary, because Nub runs TypeScript directly. Everything else maps to a Node module or an npm package below, with the node:* module first where it covers the call.
For the most-used APIs, such as Bun.file, Bun.write, and Bun.spawn, one small module that re-exports Node equivalents under the call shapes your code already uses keeps the diff in one file.
Process, shell, and system
| Bun API | Recommended replacement | Notes |
|---|---|---|
Bun.$ (shell) | dax | See shell commands above. execa for non-shell spawning. |
Bun.spawn, Bun.spawnSync | execa or node:child_process | execa is the promise-based wrapper (streaming, .pipe(), typed results); node:child_process is the zero-dependency option. Wrap either to reproduce the web-stream .stdout shape. |
Bun.which(cmd) | which | Or resolve manually against process.env.PATH with node:fs. |
Bun.openInEditor() | open or launch-editor | Opens a file in the user's editor; no Node built-in. |
Bun.env | process.env | Direct rename. |
Bun.argv | process.argv | Direct rename. |
Bun.main | process.argv[1] (resolved) or import.meta.main (Node 24+) | The entry module path. |
Bun.version, Bun.revision | process.versions, process.version | Report the Node version. |
File system and globbing
| Bun API | Recommended replacement | Notes |
|---|---|---|
Bun.file(path) | node:fs / node:fs/promises (readFile, createReadStream) | Bun.file returns a lazy Blob-like handle; the closest Node shape is fs.openAsBlob(path) (Node 20+), else readFile. |
Bun.write(path, data) | node:fs/promises writeFile | Bun.write creates parent directories; call mkdir(dirname, { recursive: true }) first. |
Bun.stdin, Bun.stdout, Bun.stderr | process.stdin / process.stdout / process.stderr | Node streams; wrap them if you read them as web streams. |
Bun.Glob | tinyglobby or fast-glob | node:fs also has glob/globSync (Node 22+) for simpler patterns. |
Bun.FileSystemRouter | find-my-way or a framework's router | Most frameworks (Next, Nitro, Hono with a file-router plugin) provide their own. |
Bun.mmap | mmap-io | A native addon. Prefer streaming reads unless you need mmap. |
HTTP, networking, and real-time
| Bun API | Recommended replacement | Notes |
|---|---|---|
Bun.serve | Hono (@hono/node-server), Fastify, or Express | node:http is the raw primitive. Hono is the closest in spirit, with web-standard Request/Response. |
Bun.serve WebSocket handler | ws | The standard Node WebSocket server. Pair it with your HTTP framework's upgrade handling. |
new WebSocket() (client) | Built in | The WebSocket client global is present under Nub. |
Bun.listen, Bun.connect (TCP) | node:net (createServer, connect) | Direct mapping. |
Bun.udpSocket | node:dgram | Direct mapping. |
Bun.dns.lookup, Bun.dns.prefetch | node:dns / node:dns/promises | Node has no prefetch; lookups map directly. |
Bun.Cookie, Bun.CookieMap | cookie (parse/serialize) | Or your framework's cookie helpers. |
Bun.CSRF.generate, Bun.CSRF.verify | csrf-csrf or csrf | Or your framework's CSRF middleware. |
fetch, Request, Response, Headers, FormData | Built in | Standard web APIs; nothing to migrate. |
Databases and storage
| Bun API | Recommended replacement | Notes |
|---|---|---|
Bun.sql, Bun.SQL (Postgres) | postgres (postgres.js) or pg | See database access above. |
bun:sqlite | better-sqlite3 or node:sqlite (Node 22.5+) | better-sqlite3 has the same synchronous prepare().get()/.all()/.run() shape as bun:sqlite. node:sqlite is the zero-dependency option, still marked experimental. |
Bun.redis, Bun.RedisClient | ioredis or redis | Full-featured Redis and Valkey clients. |
Bun.s3, Bun.S3Client | @aws-sdk/client-s3 | The official AWS SDK; works with any S3-compatible store. |
Bun.secrets | @napi-rs/keyring | OS credential stores (macOS Keychain, Windows Credential Manager, libsecret). The older keytar is archived. |
Hashing, crypto, and compression
| Bun API | Recommended replacement | Notes |
|---|---|---|
Bun.password.hash, Bun.password.verify | node:crypto scrypt or @node-rs/argon2 | Bun.password defaults to argon2id, which @node-rs/argon2 matches. bcrypt if you need bcrypt. |
Bun.hash, Bun.hash.* (non-crypto) | xxhash-wasm or node:crypto | Bun.hash is a fast non-cryptographic hash (wyhash family). Use node:crypto for a cryptographic digest. |
Bun.CryptoHasher | node:crypto createHash / createHmac | Same streaming update/digest shape. |
Bun.sha | node:crypto createHash('sha256') | One-shot SHA. |
Bun.gzipSync, Bun.gunzipSync | node:zlib (gzipSync, gunzipSync) | Direct mapping. |
Bun.deflateSync, Bun.inflateSync | node:zlib (deflateSync, inflateSync) | Direct mapping. |
Bun.zstdCompressSync, Bun.zstdDecompressSync (+ async) | node:zlib zstd (Node 22.15+ / 23.8+) | On older Node, use @mongodb-js/zstd or fzstd. |
crypto.subtle, crypto.randomUUID, crypto.getRandomValues | Built in | Standard Web Crypto. |
Build, transpile, and modules
| Bun API | Recommended replacement | Notes |
|---|---|---|
Bun.Transpiler | Not needed under Nub | To transpile a string at runtime, use oxc-transform or esbuild's transform. |
Bun.build | esbuild, tsup, or rolldown | tsup wraps esbuild for libraries; rolldown is a Rollup-compatible bundler. |
Bun.plugin (loader plugins) | The bundler's plugin API, or a module.register() hook | Bun's runtime-loader plugins have no Node equivalent. |
Bun.resolveSync | import.meta.resolve() or node:module createRequire(...).resolve | createRequire().resolve for CommonJS-style resolution. |
import.meta.dir, import.meta.file | import.meta.dirname, import.meta.filename | Node 20.11+/21.2+. See import.meta above. |
Testing
| Bun API | Recommended replacement | Notes |
|---|---|---|
bun:test | vitest or node:test | Vitest is the closest in ergonomics (describe/it/expect, watch mode, mocking). node:test with node:assert is the zero-dependency runner. |
bun:test mocking (mock, spyOn) | Vitest's vi.fn/vi.spyOn, or node:test's mock | Vitest's mocking is the nearest match. |
bun:test snapshots | Vitest snapshots | node:test has no snapshot support. |
FFI and native
| Bun API | Recommended replacement | Notes |
|---|---|---|
bun:ffi (dlopen, CString, …) | koffi | The maintained FFI library for Node, succeeding ffi-napi. |
Node-API (N-API addons) | Node-API | Works the same. Build with node-gyp, or napi-rs for Rust. |
bun:jsc (engine internals) | No equivalent | JavaScriptCore-specific. Use node:v8 or node:vm where a feature overlaps (heap snapshots, serialization). |
HTML, text, and parsing
| Bun API | Recommended replacement | Notes |
|---|---|---|
HTMLRewriter | cheerio or node-html-parser | Both parse the whole document rather than streaming it, which covers most rewrites. No maintained npm port of the streaming rewriter exists, and Nub has no built-in one. |
Bun.escapeHTML | escape-html | Single-purpose. |
Bun.stringWidth | string-width | Terminal display width (wide characters, ANSI). |
Bun.stripANSI | strip-ansi | Removes ANSI escape codes. |
Bun.wrapAnsi | wrap-ansi | ANSI-aware word wrap. |
Bun.markdown | marked or markdown-it | Markdown to HTML. |
Bun.color | culori or color | Color parsing and conversion. |
Bun.semver | semver | Bun's API is a subset. |
Bun.TOML.parse | smol-toml or @iarna/toml | TOML parsing. |
Bun.YAML.parse | yaml | YAML parsing and stringifying. |
Bun.Image | sharp | Image decode, encode, and transform. |
Utilities, timing, and inspection
| Bun API | Recommended replacement | Notes |
|---|---|---|
Bun.inspect | node:util inspect | Same depth and colors options. |
Bun.deepEquals, Bun.deepMatch | node:util isDeepStrictEqual, or dequal | isDeepStrictEqual for strict equality; dequal for a fast loose check. |
Bun.sleep, Bun.sleepSync | node:timers/promises setTimeout(ms) | await setTimeout(ms). For a synchronous sleep, Atomics.wait on a SharedArrayBuffer. |
Bun.nanoseconds | process.hrtime.bigint() | High-resolution monotonic clock. |
Bun.randomUUIDv7 | uuid (v7) | crypto.randomUUID() emits v4 only. |
Bun.peek | No equivalent | Reads a settled promise's value synchronously; restructure to await. |
Bun.fileURLToPath, Bun.pathToFileURL | node:url (fileURLToPath, pathToFileURL) | Direct mapping. |
Bun.readableStreamTo* (Text, JSON, Blob, ArrayBuffer, Bytes, Array, FormData) | Consume the web stream directly | new Response(stream).text() and its siblings cover most; Readable.fromWeb bridges to Node streams. |
Bun.ArrayBufferSink, Bun.allocUnsafe, Bun.concatArrayBuffers | Buffer (Buffer.allocUnsafe, Buffer.concat) and node:stream | A PassThrough stream for sink-style accumulation. |
Bun.gc, Bun.generateHeapSnapshot | node:v8 (writeHeapSnapshot, --expose-gc for global.gc) | Manual GC requires --expose-gc. |
Bun.indexOfLine | node:readline | Line scanning over the stream. |
Bun.cron (scheduling) | croner or node-cron | In-process cron scheduling; croner has no dependencies. |
Production server and Docker
If your server targets Bun, such as Nitro's bun preset, switch to its Node target (node-server or node). The Docker base image becomes a Node image with Nub installed:
FROM node:27-slim
RUN npm install -g @nubjs/nub
# ... copy app, nub install, build ...
CMD ["node", ".output/server/index.mjs"]A built, already-transpiled server bundle runs on plain node. Nub does the build-stage work: installing, running scripts, and running TypeScript entry points. See Docker.
CI and Dependabot
- CI — replace the Bun setup action with setup-nub.
- Dependabot and Renovate — neither supports Nub directly. Use
package-ecosystem: "npm"and add a workflow step that runsnub installafter the bot's update, so the lockfile stays in sync withpackage.json.
Supply-chain cooldown
Bun's [install].minimumReleaseAge refuses package versions newer than a threshold, and Nub honors the same gate. Nub reads it from bunfig.toml and converts Bun's seconds to minutes, rounding up. Bun's minimumReleaseAgeExcludes maps to Nub's minimumReleaseAgeExclude.
In .npmrc, the setting is in minutes:
# .npmrc
minimum-release-age=1440 # one dayGotchas
- Bun's
[install].linkeris not read. Choose a layout withinstall.linkerinnub.jsonc,node-linkerin.npmrc, or the--node-linkerflag. See layout settings. - Memory use is higher. Node generally uses more memory than Bun for the same parallel fan-out. If heavy tasks such as type checking, linting, and tests hit out-of-memory kills after the move, run fewer at once.