Node.js 相容性
Bun 對 Node.js API、模組和全域性變數的相容狀態
Bun 每天都在向實現 100% 的 Node.js API 相容性邁進。Next.js、Express 等熱門框架,以及數百萬個面向 Node.js 的 npm 包,都可以在 Bun 中執行。為確保相容性,我們會在每次釋出 Bun 之前,執行 Node.js 測試套件中的數千項測試。
如果某個包在 Node.js 中可以執行,但在 Bun 中無法執行,我們會將其視為 Bun 的 bug。 提交問題,我們會修復它。
我們會定期更新此頁面。它反映了 Bun 與 Node.js v26 相容性的最新狀態。
內建 Node.js 模組
node:assert
🟢 完全實現。舊版模式的 deepEqual 使用 Bun.deepEquals 語義,而不是 Node 的寬鬆 == 比較,並且函式值或 printf 風格的 message 引數不會進行格式化。
node:buffer
🟢 完全實現。單個 Buffer 的上限為 4 GiB(buffer.constants.MAX_LENGTH 為 2**32)。
node:console
🟢 完全實現。Bun 會直接將控制台輸出寫入 stdout/stderr 檔案描述符,並使用自己的檢查器進行格式化。因此,替換 process.stdout.write 無法捕獲輸出,並且物件佈局與 util.inspect 不同。console.trace() 會寫入 stdout,而 console.time*() 會寫入 stderr。
node:dgram
🟢 完全實現。Node.js 測試套件通過率為 99%。addMembership() 不會隱式繫結未繫結的套接字;請先呼叫 bind()。
node:diagnostics_channel
🟡 已實現 channel()、subscribe()、tracingChannel() 以及 http 客戶端、http2 和 dgram 內建通道。缺少 boundedChannel() 以及 http.server.*、net、module、console、child_process 和 worker_threads 內建通道。訂閱者不會使 Channel 保持存活,因此請保留對它的引用。
node:dns
🟢 完全實現。缺少 resolveTlsa。Bun 會忽略 Resolver 的 maxTimeout 選項。
node:events
🟢 完全實現。Node.js 測試套件通過率為 95%。EventEmitterAsyncResource 底層使用 AsyncResource,因此其 asyncId 始終為 0。
node:fs
🟢 完全實現。Node.js 測試套件通過率為 98%。Stats 物件缺少 Temporal.Instant getter(atimeInstant 等)。
node:http
🟢 完全實現。http.Server 不會繼承 net.Server。Bun 會忽略 listen(handle) 以及 listen() 的 fd、ipv6Only 和 signal 選項。伺服器上的 keepAlive/keepAliveInitialDelay 不執行任何操作。
node:https
🟡 已實現 request、get、Agent 和 globalAgent,包括連線池。客戶端套接字是 tls.TLSSocket。https.Server 是帶有 TLS 選項的 http.Server,而不是 tls.Server。其請求套接字(req.socket)不是 tls.TLSSocket:encrypted、authorized 和 servername 可用,但缺少 getPeerCertificate() 和 getCipher()。不支援 setSecureContext()、addContext()、SNICallback 和 handshakeTimeout。
node:os
🟢 完全實現。userInfo() 從環境變數(USER、SHELL、HOME)中讀取 username、shell 和 homedir,而不是從 passwd 資料庫讀取。在 Linux arm64 上,machine() 傳回 "arm64" 而不是 "aarch64"。
node:path
🟢 完全實現。matchesGlob() 使用 Bun.Glob 語義,而不是 minimatch(* 會匹配點檔案,不支援 extglobs)。在涉及裝置路徑和保留名稱的少數邊緣情況下,path.win32 與 Node 有所不同。
node:punycode
🟢 完全實現。Node.js 測試套件 100% 通過。已被 Node.js 棄用。
node:querystring
🟢 完全實現。Node.js 測試套件 100% 通過。
node:readline
🟢 完全實現。
node:stream
🟢 完全實現。isReadable、isWritable、isErrored 和 Readable.isDisturbed 只理解 Node.js 流,不理解 web 流。
node:string_decoder
🟢 完全實現。Node.js 測試套件 100% 通過。end() 不接受字串引數。
node:timers
🟢 完全實現。匯出的函式與全域性函式相同。node:timers/promises(包括 scheduler.wait() 和 scheduler.yield())也已實現。
node:tty
🟢 完全實現。ReadStream 和 WriteStream 繼承的是 fs 流,而不是 net.Socket;在非 TTY fd 上構造它們時,會傳回 isTTY 設定為 false 的流,而不是丟擲異常。
node:url
🟢 完全實現。
node:zlib
🟢 完全實現。Node.js 測試套件通過率為 98%。
node:async_hooks
🟡 已實現 AsyncLocalStorage 和 AsyncResource。createHook、executionAsyncId、triggerAsyncId 和 executionAsyncResource 是存根:除了 process.nextTick 的 init 事件之外,Bun 不會呼叫鉤子,並且非同步 ID 始終為 0。Node.js 強烈不建議使用這些 API,建議改用 AsyncLocalStorage。Bun 不會將 AsyncLocalStorage 上下文傳播到 MessagePort、BroadcastChannel 或 Worker 事件中。
node:child_process
🟡 IPC 可以傳送 net.Socket、net.Server 和 dgram.Socket 控制代碼(包括向 Node.js 行程傳送和從 Node.js 行程接收),但不能傳送 http 伺服器套接字。serialization: "advanced" 僅適用於 Bun 行程之間,因此 Node.js 與 Bun 之間的 IPC 請使用 JSON 序列化。缺少 subprocess.channel.ref()/unref()。無法將某個子行程的 stdout/stderr 作為另一個子行程的 stdio 傳入,並且 spawnSync 不會在 output 中傳回額外的 stdio 管道。
node:cluster
🟡 worker 中的 net 和 dgram 伺服器會像 Node.js 中一樣通過 primary 共享(SCHED_RR 和 SCHED_NONE),並且可以通過 worker.send() 傳遞控制代碼。worker 中的 node:http/node:https 伺服器會分別繫結自己的套接字,因此只有在 Linux 上(通過 SO_REUSEPORT)才支援跨行程對 HTTP 請求進行負載均衡。除此之外已實現,但尚未經過充分測試。
node:crypto
🟡 缺少 encapsulate/decapsulate(可以通過 crypto.subtle 使用 ML-KEM 金鑰)。已實現 argon2() 和 argon2Sync()。自定義引擎(setEngine())會丟擲異常,setFips() 不執行任何操作,而 secureHeapUsed() 傳回 undefined。Bun 的加密功能基於 BoringSSL,後者不支援 ed448、x448、rsa-pss、dsa、dh 和 ml-kem-512 金鑰型別;除 P-224/256/384/521 之外的 EC 曲線(不支援 secp256k1);以及 CCM、OCB、XTS 和 chacha20-poly1305 密碼演算法。DiffieHellman 類(createDiffieHellman()、getDiffieHellman())可用。
node:domain
🟡 缺少 Domain members。domain 只會捕獲在 run()/bind() 內同步丟擲的錯誤,或傳遞給 add() 的事件發射器發出的錯誤。Bun 不會將來自計時器、process.nextTick、promise 和其他非同步回撥的錯誤路由到 domain。
node:http2
🟢 客戶端和伺服器均已實現。Node.js 測試套件通過率為 94%。maxDeflateDynamicTableSize、peerMaxConcurrentStreams 和 streamResetBurst/streamResetRate 選項會被接受但忽略。
node:module
🟡 缺少 Module#load()、registerHooks、findPackageJSON、stripTypeScriptTypes、getSourceMapsSupport/setSourceMapsSupport。支援覆蓋 require.cache、require.extensions 和 module._resolveFilename。syncBuiltinESMExports、module._load、module._pathCache 和 module.register 不執行任何操作(我們建議改用 Bun.plugin)。findSourceMap 始終傳回 undefined。
node:net
🟢 完全實現,包括 BlockList、SocketAddress、autoSelectFamily、Unix 域套接字和 server.listen({ fd })。new net.Socket({ fd }) 無法從現有檔案描述符讀取(只能進行只寫封裝)。server.listen(handle) 只接受 { fd }。缺少 blockList.toJSON()/fromJSON()。
node:perf_hooks
🟡 已實現 monitorEventLoopDelay()、createHistogram()、timerify() 和 PerformanceObserver(mark、measure、function、net、http 和 http2 條目)。Bun 永遠不會發出 gc、dns 或 resource 條目。eventLoopUtilization() 始終傳回零,而 performance.nodeTiming 包含佔位值。只有匯入 node:perf_hooks 後,全域性 performance 物件才會出現 Node 專屬的擴充套件。
node:process
🟡 參見 process 全域性變數部分。
node:sys
🟢 參見 node:util。
node:tls
🟡 缺少 pskCallback、OCSP 裝訂(requestOCSP)、伺服器的 'newSession'/'resumeSession' 事件以及會話票據金鑰(ticketKeys 會被忽略)。因此,跨行程的會話恢復無法使用。Bun 使用 BoringSSL,因此 tlsSocket.renegotiate() 始終會失敗,而 getEphemeralKeyInfo()/getSharedSigalgs() 不會傳回任何資訊。
node:util
🟢 完全實現。缺少 diff(在 Node.js 中為實驗性功能)、transferableAbortSignal 和 transferableAbortController。debuglog() 會忽略其 callback 引數,且傳回的函式沒有 enabled 屬性。
node:v8
🟡 已實現 writeHeapSnapshot、getHeapSnapshot、getHeapStatistics、getHeapSpaceStatistics、GCProfiler 和 startupSnapshot。堆統計資訊描述的是 JavaScriptCore 的單個堆,並且 setFlagsFromString 會忽略傳入的標誌。serialize 和 deserialize 使用 JavaScriptCore 的線格式,而不是 V8 的格式。缺少 queryObjects、startCpuProfile、startHeapProfile、Serializer/Deserializer、takeCoverage/stopCoverage 和 promiseHooks。如需效能分析,請改用 bun:jsc。
node:vm
🟢 完全實現,包括 vm.Script、vm.createContext、vm.runInContext、vm.runInNewContext、vm.runInThisContext、vm.compileFunction、vm.isContext、ES 模組類 vm.Module、vm.SourceTextModule 和 vm.SyntheticModule(無需 --experimental-vm-modules 即可匯出),以及對 importModuleDynamically 的支援。支援 timeout、breakOnSigint、cachedData、microtaskMode 和 codeGeneration 選項。如果 importModuleDynamically 回撥傳回一個解析為 vm.Module 的 promise,import() 會解析為模組物件,而不是其名稱空間。vm.measureMemory() 會報告每個上下文的整個堆資料。
node:wasi
🟡 部分實現。WASI 支援 args、env、preopens、wasiImport 和 start(),並且 bun ./program.wasm 可以直接執行 WASI 命令。缺少 getImportObject()(請使用 wasiImport)、initialize() 和 sock_accept 匯入項。Bun 會忽略 version、returnOnExit、stdin、stdout 和 stderr 選項,因此 proc_exit 會退出 Bun 行程。
node:worker_threads
🟡 Worker 會忽略 resourceLimits 和 trackUnmanagedFds 選項。部分 execArgv 標誌會在 worker 中生效,例如 --no-addons、--stack-trace-limit 和 --tls-min-v1.3。其他標誌,例如 --conditions 和 --no-deprecation,只會設定 process.execArgv。worker.performance.eventLoopUtilization() 是存根。缺少 moveMessagePortToContext 和 locks。
node:inspector
🟡 部分實現。Session 支援 Profiler 域(包括精確覆蓋率)、Runtime.enable 和 NodeTracing,可通過 node:inspector 和 node:inspector/promises 使用。呼叫 open() 後,Session 還會將 Debugger.enable 和 Debugger.setBreakpointByUrl 等 Debugger 設定命令轉發到檢查器伺服器。不會傳回諸如 breakpointId 之類的結果。其他 Session 命令(例如 Runtime.evaluate)和 HeapProfiler 域尚未實現。open()、url()、close() 和 waitForDebugger() 均已實現。open() 會提供 Debugger 和 Runtime 域,並且在 worker 中會丟擲異常。缺少 Network。
node:repl
🟡 大部分已實現。bun --interactive 會啟動相容 Node.js 的 REPL。REPL 不會顯示結果預覽(這需要基於 V8 檢查器的無副作用求值)。Tab 自動補全會跳過 let/const/class 繫結,並且部分 V8 專屬錯誤訊息和堆疊幀措辭有所不同。
node:sqlite
🟢 完全實現。backup() 同步執行,並會在複製期間阻塞事件迴圈(Node 會在 worker 執行緒中執行它)。Buffer/Uint8Array 資料庫路徑必須是有效的 UTF-8(Node 會原樣傳遞原始位元組;Bun 會對非 UTF-8 路徑丟擲 ERR_INVALID_ARG_VALUE)。在 macOS 上,Bun 使用系統的 libsqlite3.dylib。loadExtension() 需要完整的 SQLite 建置版本,較舊 macOS 版本上的 createSession()/applyChangeset() 也需要該版本。如需使用完整的 SQLite 建置版本,請在開啟資料庫前呼叫 require("bun:sqlite").Database.setCustomSQLite(path)。
node:test
🟡 部分實現。在測試檔案通過 bun test 執行環境,行程內 API 可用:tests、suites、subtests、hooks、t.plan()、t.assert、assert.register()、t.waitFor()、getTestContext()、expectFailure 和 t.mock(函式/方法/getter/setter/屬性 mock 和 mock 計時器)。run() 需要顯式的 files 列表,並會在 bun test 子行程中執行每個檔案。其大多數選項(globPatterns、watch、coverage、shard、only、testNamePatterns 等)都會丟擲 ERR_NOT_IMPLEMENTED。缺少 node:test/reporters、快照測試、mock.module()、t.runOnly()、程式碼覆蓋率、--test-only、測試級別的 signal 中止功能,以及 Node 的 --test CLI 執行模式。雖然接受 test.only()/{only: true},但不會據此篩選測試。concurrency 會經過驗證,但 subtests 始終序列執行。請改用 bun:test。
node:trace_events
🟢 完全實現。支援 createTracing()、getEnabledCategories() 以及 --trace-events-enabled、--trace-event-categories 和 --trace-event-file-pattern 標誌。Bun 會在退出時寫入跟蹤資料。部分類別記錄的資訊少於 Node.js。例如,node.async_hooks 只記錄計時器,而 v8 類別僅為佔位項,因為 JavaScriptCore 沒有 V8 GC 或編譯事件。
node:quic
🟢 已實現:listen()、connect()、QuicEndpoint、QuicSession 和 QuicStream。Node.js 測試套件通過率為 99%。該 API 在 Node.js 中屬於實驗性功能,在 Bun 中匯入它也會發出 ExperimentalWarning。
node:sea
🔴 未實現。請改用 bun build --compile 建置單檔案可執行程式。
Node.js 全域性變數
以下列表涵蓋 Node.js 實現的全域性變數,以及 Bun 對每一項的相容狀態。
AbortController
🟢 完全實現。
AbortSignal
🟢 完全實現。
Blob
🟢 完全實現。建構函式的 endings 選項會被忽略,並且 blob.stream() 不支援 BYOB reader。
Buffer
🟢 完全實現。單個 Buffer 的上限為 4 GiB(buffer.constants.MAX_LENGTH 為 2**32)。
ByteLengthQueuingStrategy
🟢 完全實現。
__dirname
🟢 完全實現。
__filename
🟢 完全實現。
atob()
🟢 完全實現。
Atomics
🟢 完全實現。
BroadcastChannel
🟢 完全實現。
btoa()
🟢 完全實現。
clearImmediate()
🟢 完全實現。
clearInterval()
🟢 完全實現。
clearTimeout()
🟢 完全實現。
CloseEvent
🟢 完全實現。
CompressionStream
🟢 完全實現。
console
🟢 完全實現。關於輸出寫入方式的差異,請參閱 node:console。
CountQueuingStrategy
🟢 完全實現。
Crypto
🟢 完全實現。
SubtleCrypto (crypto)
🟢 完全實現。Bun 不支援的演算法請參閱 SubtleCrypto。
CryptoKey
🟢 完全實現。
CustomEvent
🟢 完全實現。
DecompressionStream
🟢 完全實現。
ErrorEvent
🟢 完全實現。
Event
🟢 完全實現。
EventTarget
🟢 完全實現。
exports
🟢 完全實現。
fetch
🟢 完全實現。integrity 選項會被忽略。
File
🟢 完全實現。File 物件會將 Blob 報告為其 constructor 和 Symbol.toStringTag。
FormData
🟢 完全實現。
global
🟢 已實現。global 是一個包含全域性名稱空間中所有物件的物件。它很少會被直接引用,因為其中的內容無需字首即可使用,例如使用 console 而不是 global.console。
globalThis
🟢 是指向 global 的別名。
Headers
🟢 完全實現。
MessageChannel
🟢 完全實現。
MessageEvent
🟢 完全實現。
MessagePort
🟢 完全實現。Node.js 新增的 EventEmitter 風格方法(on()、once()、off() 等)只有在載入 node:worker_threads 後才會安裝。
module
🟢 完全實現。缺少 module.isPreloading。
navigator
🟡 已實現 userAgent、platform 和 hardwareConcurrency。缺少 language、languages 和 locks。Navigator 類不是全域性變數。
PerformanceEntry
🟢 完全實現。
PerformanceMark
🟢 完全實現。
PerformanceMeasure
🟢 完全實現。
PerformanceObserver
🟡 可以觀察 mark 和 measure 條目。Bun 只會將 Node 專屬條目型別(function、http、net 等)傳遞給 node:perf_hooks 的 PerformanceObserver,並且永遠不會發出 gc、dns 或 resource 條目。
PerformanceObserverEntryList
🟢 完全實現。
PerformanceResourceTiming
🟡 該類存在,但永遠不會建立條目:fetch() 不會記錄資源計時資訊,並且 performance.markResourceTiming() 不執行任何操作。
performance
🟡 已實現 now()、timeOrigin、mark()、measure() 和 getEntries()。只有載入 node:perf_hooks 後,Node.js 擴充套件項(eventLoopUtilization()、nodeTiming、timerify())才會存在。eventLoopUtilization() 始終傳回零,而 nodeTiming 包含佔位值。
process
🟡 大部分已實現。process.binding(某些包所相依的 Node.js 內部繫結)部分實現:可用項包括 buffer、config、constants、crypto/x509、fs、http_parser、natives、tty_wrap、util 和 uv,其餘項會丟擲異常。在 macOS 和 Linux 上設定 process.title 不執行任何操作。getActiveResourcesInfo()、_getActiveHandles() 和 _getActiveRequests() 始終傳回空陣列,setSourceMapsEnabled() 不執行任何操作,並且 process.report.writeReport() 不會寫入任何內容。缺少 sourceMapsEnabled 和 addUncaughtExceptionCaptureCallback。
queueMicrotask()
🟢 完全實現。
QuotaExceededError
🔴 未實現。
ReadableByteStreamController
🟢 完全實現。
ReadableStream
🟢 完全實現。無法通過 postMessage() 或 structuredClone() 傳輸流。
ReadableStreamBYOBReader
🟢 完全實現。
ReadableStreamBYOBRequest
🟢 完全實現。
ReadableStreamDefaultController
🟢 完全實現。
ReadableStreamDefaultReader
🟢 完全實現。
require()
🟢 完全實現,包括 require.main、require.cache、require.resolve。
Response
🟢 完全實現。由字串構造的 Response 不會在 headers 中公開預設的 content-type 標頭(Bun.serve() 仍會發送該標頭)。
Request
🟡 缺少 keepalive 和 duplex。credentials、integrity、referrer 和 referrerPolicy 選項會被接受但忽略。
setImmediate()
🟢 完全實現。
setInterval()
🟢 完全實現。
setTimeout()
🟢 完全實現。
structuredClone()
🟢 完全實現。只有 ArrayBuffer 和 MessagePort 可以被傳輸,並且克隆的 Error 會丟失其 cause。
Storage
🔴 未實現。Bun 沒有 Storage、localStorage 或 sessionStorage 全域性變數。
SubtleCrypto
🟢 完全實現,包括 supports()、getPublicKey()、encapsulate*()/decapsulate*() 方法、ML-DSA、ML-KEM-768/ML-KEM-1024、SHA3-* 和 ChaCha20-Poly1305。缺少 Ed448、X448、AES-OCB、Argon2*、cSHAKE*、KMAC*、KT128/KT256、TurboSHAKE* 和 ML-KEM-512 演算法(這些演算法在 Node.js 中均為實驗性功能)。
DOMException
🟢 完全實現。例項不是原生錯誤(Error.isError() 傳回 false)。
TextDecoder
🟢 完全實現。
TextDecoderStream
🟢 完全實現。
TextEncoder
🟢 完全實現。
TextEncoderStream
🟢 完全實現。
TransformStream
🟢 完全實現。無法通過 postMessage() 或 structuredClone() 傳輸。
TransformStreamDefaultController
🟢 完全實現。
URL
🟢 完全實現。
URLPattern
🟢 完全實現。
URLSearchParams
🟢 完全實現。
WebAssembly
🟢 完全實現。Memory64 預設處於停用狀態(設定 BUN_JSC_useWasmMemory64=1 可啟用)。
WebSocket
🟢 完全實現。binaryType 預設為 "nodebuffer",因此二進位制訊息會以 Buffer 的形式到達。Node.js 的預設值為 "blob"。
WritableStream
🟢 完全實現。無法通過 postMessage() 或 structuredClone() 傳輸。
WritableStreamDefaultController
🟢 完全實現。
WritableStreamDefaultWriter
🟢 完全實現。