Skip to content

Bun.version

一個包含當前運行的 bun CLI 版本的字符串。

ts
Bun.version;
// => "1.3.3"

Bun.revision

編譯當前 bun CLI 所使用的 Bun 的 git 提交哈希。

ts
Bun.revision;
// => "f02561530fda1ee9396f51c8bc99b38716e38296"

Bun.env

process.env 的別名。

Bun.main

當前程序入口點的絕對路徑(使用 bun run 執行的文件)。

ts
Bun.main;
// /path/to/script.ts

這對於確定腳本是直接執行還是被另一個腳本導入特別有用。

ts
if (import.meta.path === Bun.main) {
  // 此腳本正在直接執行
} else {
  // 此文件正從另一個腳本導入
}

這類似於 Node.js 中的 require.main = module 技巧

Bun.sleep()

Bun.sleep(ms: number)

返回一個在給定毫秒數後解析的 Promise

ts
console.log("hello");
await Bun.sleep(1000);
console.log("hello 一秒後!");

或者,傳遞一個 Date 對象來返回一個在該時間點解析的 Promise

ts
const oneSecondInFuture = new Date(Date.now() + 1000);

console.log("hello");
await Bun.sleep(oneSecondInFuture);
console.log("hello 一秒後!");

Bun.sleepSync()

Bun.sleepSync(ms: number)

Bun.sleep 的阻塞同步版本。

ts
console.log("hello");
Bun.sleepSync(1000); // 阻塞線程一秒
console.log("hello 一秒後!");

Bun.which()

Bun.which(bin: string)

返回可執行文件的路徑,類似於在終端中輸入 which

ts
const ls = Bun.which("ls");
console.log(ls); // "/usr/bin/ls"

默認情況下,Bun 會查看當前的 PATH 環境變量來確定路徑。要配置 PATH

ts
const ls = Bun.which("ls", {
  PATH: "/usr/local/bin:/usr/bin:/bin",
});
console.log(ls); // "/usr/bin/ls"

傳遞 cwd 選項以從特定目錄內解析可執行文件。

ts
const ls = Bun.which("ls", {
  cwd: "/tmp",
  PATH: "",
});

console.log(ls); // null

你可以將其視為 which npm 包的內置替代方案。

Bun.randomUUIDv7()

Bun.randomUUIDv7() 返回一個 UUID v7,它是單調的,適用於排序和數據庫。

ts
import { randomUUIDv7 } from "bun";

const id = randomUUIDv7();
// => "0192ce11-26d5-7dc3-9305-1426de888c5a"

UUID v7 是一個 128 位的值,編碼了當前時間戳、隨機值和計數器。時間戳使用最低的 48 位編碼,隨機值和計數器使用剩余的位編碼。

timestamp 參數默認為當前時間(毫秒)。當時間戳變化時,計數器重置為包裝到 4096 的偽隨機整數。此計數器是原子且線程安全的,這意味著在同一進程中相同時間戳運行的多個 Worker 中使用 Bun.randomUUIDv7() 不會有沖突的計數器值。

UUID 的最後 8 個字節是加密安全的隨機值。它使用與 crypto.randomUUID() 相同的隨機數生成器(來自 BoringSSL,後者又來自底層硬件通常提供的平台特定系統隨機數生成器)。

ts
namespace Bun {
  function randomUUIDv7(encoding?: "hex" | "base64" | "base64url" = "hex", timestamp?: number = Date.now()): string;
  /**
   * 如果傳遞 "buffer",你會得到一個 16 字節的緩沖區而不是字符串。
   */
  function randomUUIDv7(encoding: "buffer", timestamp?: number = Date.now()): Buffer;

  // 如果只傳遞時間戳,你會得到一個十六進制字符串
  function randomUUIDv7(timestamp?: number = Date.now()): string;
}

你可以選擇將編碼設置為 "buffer" 來獲得一個 16 字節的緩沖區而不是字符串。這有時可以避免字符串轉換開銷。

ts
const buffer = Bun.randomUUIDv7("buffer");

當你想要更短的字符串時,還支持 base64base64url 編碼。

ts
const base64 = Bun.randomUUIDv7("base64");
const base64url = Bun.randomUUIDv7("base64url");

Bun.peek()

Bun.peek(prom: Promise)

讀取 Promise 的結果而無需 await.then,但僅當 Promise 已經履行或拒絕時。

ts
import { peek } from "bun";

const promise = Promise.resolve("hi");

// 無需 await!
const result = peek(promise);
console.log(result); // "hi"

這在嘗試減少性能敏感代碼中多余的微任務數量時很重要。這是一個高級 API,除非你知道自己在做什麼,否則可能不應該使用它。

ts
import { peek } from "bun";
import { expect, test } from "bun:test";

test("peek", () => {
  const promise = Promise.resolve(true);

  // 無需 await!
  expect(peek(promise)).toBe(true);

  // 如果我們再次 peek,它返回相同的值
  const again = peek(promise);
  expect(again).toBe(true);

  // 如果我們 peek 一個非 Promise,它返回該值
  const value = peek(42);
  expect(value).toBe(42);

  // 如果我們 peek 一個待決的 Promise,它再次返回該 Promise
  const pending = new Promise(() => {});
  expect(peek(pending)).toBe(pending);

  // 如果我們 peek 一個被拒絕的 Promise,它:
  // - 返回錯誤
  // - 不將 Promise 標記為已處理
  const rejected = Promise.reject(new Error("成功測試 Promise 拒絕"));
  expect(peek(rejected).message).toBe("成功測試 Promise 拒絕");
});

peek.status 函數讓你讀取 Promise 的狀態而無需解析它。

ts
import { peek } from "bun";
import { expect, test } from "bun:test";

test("peek.status", () => {
  const promise = Promise.resolve(true);
  expect(peek.status(promise)).toBe("fulfilled");

  const pending = new Promise(() => {});
  expect(peek.status(pending)).toBe("pending");

  const rejected = Promise.reject(new Error("哦不"));
  expect(peek.status(rejected)).toBe("rejected");
});

Bun.openInEditor()

在你的默認編輯器中打開文件。Bun 通過 $VISUAL$EDITOR 環境變量自動檢測你的編輯器。

ts
const currentFile = import.meta.url;
Bun.openInEditor(currentFile);

你可以通過 bunfig.toml 中的 debug.editor 設置覆蓋此設置。

toml
[debug] 
editor = "code"

或者使用 editor 參數指定編輯器。你還可以指定行號和列號。

ts
Bun.openInEditor(import.meta.url, {
  editor: "vscode", // 或 "subl"
  line: 10,
  column: 5,
});

Bun.deepEquals()

遞歸檢查兩個對象是否相等。這是 bun:testexpect().toEqual() 內部使用的。

ts
const foo = { a: 1, b: 2, c: { d: 3 } };

// true
Bun.deepEquals(foo, { a: 1, b: 2, c: { d: 3 } });

// false
Bun.deepEquals(foo, { a: 1, b: 2, c: { d: 4 } });

第三個布爾參數可用於啟用"嚴格"模式。這是測試運行器中 expect().toStrictEqual() 使用的。

ts
const a = { entries: [1, 2] };
const b = { entries: [1, 2], extra: undefined };

Bun.deepEquals(a, b); // => true
Bun.deepEquals(a, b, true); // => false

在嚴格模式下,以下被視為不相等:

ts
// undefined 值
Bun.deepEquals({}, { a: undefined }, true); // false

// 數組中的 undefined
Bun.deepEquals(["asdf"], ["asdf", undefined], true); // false

// 稀疏數組
Bun.deepEquals([, 1], [undefined, 1], true); // false

// 對象字面量與具有相同屬性的實例
class Foo {
  a = 1;
}
Bun.deepEquals(new Foo(), { a: 1 }, true); // false

Bun.escapeHTML()

Bun.escapeHTML(value: string | object | number | boolean): string

從輸入字符串中轉義以下字符:

  • " 變為 "
  • & 變為 &
  • ' 變為 '
  • < 變為 <
  • > 變為 >

此函數針對大輸入進行了優化。在 M1X 上,它處理速度為 480 MB/s - 20 GB/s,具體取決於要轉義的數據量以及是否有非 ASCII 文本。非字符串類型在轉義之前將轉換為字符串。

Bun.stringWidth()

NOTE

比 `string-width` 快約 6,756 倍的替代方案

獲取字符串在終端中顯示時的列數。支持 ANSI 轉義碼、emoji 和寬字符。

示例用法:

ts
Bun.stringWidth("hello"); // => 5
Bun.stringWidth("\u001b[31mhello\u001b[0m"); // => 5
Bun.stringWidth("\u001b[31mhello\u001b[0m", { countAnsiEscapeCodes: true }); // => 12

這對於以下用途很有用:

  • 在終端中對齊文本
  • 快速檢查字符串是否包含 ANSI 轉義碼
  • 測量終端中字符串的寬度

此 API 設計為與流行的 "string-width" 包匹配,以便現有代碼可以輕松移植到 Bun,反之亦然。

在此基准測試中,對於大於約 500 個字符的輸入,Bun.stringWidthstring-width npm 包快約 6,756 倍。非常感謝 sindresorhusstring-width 上的工作!

ts
❯ bun string-width.mjs
cpu: 13th Gen Intel(R) Core(TM) i9-13900
runtime: bun 1.0.29 (x64-linux)

benchmark                                          time (avg)             (min … max)       p75       p99      p995
------------------------------------------------------------------------------------- -----------------------------
Bun.stringWidth     500 chars ascii              37.09 ns/iter   (36.77 ns … 41.11 ns)  37.07 ns  38.84 ns  38.99 ns

❯ node string-width.mjs

benchmark                                          time (avg)             (min … max)       p75       p99      p995
------------------------------------------------------------------------------------- -----------------------------
npm/string-width    500 chars ascii             249,710 ns/iter (239,970 ns … 293,180 ns) 250,930 ns  276,700 ns 281,450 ns

為了使 Bun.stringWidth 快速,我們使用優化的 SIMD 指令在 Zig 中實現了它,考慮了 Latin1、UTF-16 和 UTF-8 編碼。它通過了 string-width 的測試。

查看完整基准測試">

提醒一下,1 納秒 (ns) 是 10 億分之一秒。以下是單位轉換的快速參考:

單位1 毫秒
ns1,000,000
µs1,000
ms1
bash
 bun string-width.mjs
cpu: 13th Gen Intel(R) Core(TM) i9-13900
runtime: bun 1.0.29 (x64-linux)

benchmark                                          time (avg)             (min max)       p75       p99      p995
------------------------------------------------------------------------------------- -----------------------------
Bun.stringWidth      5 chars ascii              16.45 ns/iter   (16.27 ns 19.71 ns)  16.48 ns  16.93 ns  17.21 ns
Bun.stringWidth     50 chars ascii              19.42 ns/iter   (18.61 ns 27.85 ns)  19.35 ns   21.7 ns  22.31 ns
Bun.stringWidth    500 chars ascii              37.09 ns/iter   (36.77 ns 41.11 ns)  37.07 ns  38.84 ns  38.99 ns
Bun.stringWidth  5,000 chars ascii              216.9 ns/iter  (215.8 ns 228.54 ns) 216.23 ns 228.52 ns 228.53 ns
Bun.stringWidth 25,000 chars ascii               1.01 µs/iter     (1.01 µs 1.01 µs)   1.01 µs   1.01 µs   1.01 µs
Bun.stringWidth      7 chars ascii+emoji         54.2 ns/iter   (53.36 ns 58.19 ns)  54.23 ns  57.55 ns  57.94 ns
Bun.stringWidth     70 chars ascii+emoji       354.26 ns/iter (350.51 ns 363.96 ns) 355.93 ns 363.11 ns 363.96 ns
Bun.stringWidth    700 chars ascii+emoji          3.3 µs/iter      (3.27 µs 3.4 µs)    3.3 µs    3.4 µs    3.4 µs
Bun.stringWidth  7,000 chars ascii+emoji        32.69 µs/iter   (32.22 µs 45.27 µs)   32.7 µs  34.57 µs  34.68 µs
Bun.stringWidth 35,000 chars ascii+emoji       163.35 µs/iter (161.17 µs 170.79 µs) 163.82 µs 169.66 µs 169.93 µs
Bun.stringWidth      8 chars ansi+emoji         66.15 ns/iter   (65.17 ns 69.97 ns)  66.12 ns   69.8 ns  69.87 ns
Bun.stringWidth     80 chars ansi+emoji        492.95 ns/iter  (488.05 ns 499.5 ns)  494.8 ns 498.58 ns  499.5 ns
Bun.stringWidth    800 chars ansi+emoji          4.73 µs/iter     (4.71 µs 4.88 µs)   4.72 µs   4.88 µs   4.88 µs
Bun.stringWidth  8,000 chars ansi+emoji         47.02 µs/iter   (46.37 µs 67.44 µs)  46.96 µs  49.57 µs  49.63 µs
Bun.stringWidth 40,000 chars ansi+emoji        234.45 µs/iter (231.78 µs 240.98 µs) 234.92 µs 236.34 µs 236.62 µs
Bun.stringWidth     19 chars ansi+emoji+ascii  135.46 ns/iter (133.67 ns 143.26 ns) 135.32 ns 142.55 ns 142.77 ns
Bun.stringWidth    190 chars ansi+emoji+ascii    1.17 µs/iter     (1.16 µs 1.17 µs)   1.17 µs   1.17 µs   1.17 µs
Bun.stringWidth  1,900 chars ansi+emoji+ascii   11.45 µs/iter   (11.26 µs 20.41 µs)  11.45 µs  12.08 µs  12.11 µs
Bun.stringWidth 19,000 chars ansi+emoji+ascii  114.06 µs/iter (112.86 µs 120.06 µs) 114.25 µs 115.86 µs 116.15 µs
Bun.stringWidth 95,000 chars ansi+emoji+ascii  572.69 µs/iter (565.52 µs 607.22 µs) 572.45 µs 604.86 µs 605.21 µs
bash
 node string-width.mjs
cpu: 13th Gen Intel(R) Core(TM) i9-13900
runtime: node v21.4.0 (x64-linux)

benchmark                                           time (avg)             (min max)       p75       p99      p995
-------------------------------------------------------------------------------------- -----------------------------
npm/string-width      5 chars ascii               3.19 µs/iter     (3.13 µs 3.48 µs)   3.25 µs   3.48 µs   3.48 µs
npm/string-width     50 chars ascii              20.09 µs/iter  (18.93 µs 435.06 µs)  19.49 µs  21.89 µs  22.59 µs
npm/string-width    500 chars ascii             249.71 µs/iter (239.97 µs 293.18 µs) 250.93 µs  276.7 µs 281.45 µs
npm/string-width  5,000 chars ascii               6.69 ms/iter     (6.58 ms 6.76 ms)   6.72 ms   6.76 ms   6.76 ms
npm/string-width 25,000 chars ascii             139.57 ms/iter (137.17 ms 143.28 ms) 140.49 ms 143.28 ms 143.28 ms
npm/string-width      7 chars ascii+emoji          3.7 µs/iter     (3.62 µs 3.94 µs)   3.73 µs   3.94 µs   3.94 µs
npm/string-width     70 chars ascii+emoji        23.93 µs/iter   (22.44 µs 331.2 µs)  23.15 µs  25.98 µs   30.2 µs
npm/string-width    700 chars ascii+emoji       251.65 µs/iter (237.78 µs 444.69 µs) 252.92 µs 325.89 µs 354.08 µs
npm/string-width  7,000 chars ascii+emoji         4.95 ms/iter     (4.82 ms 5.19 ms)      5 ms   5.04 ms   5.19 ms
npm/string-width 35,000 chars ascii+emoji        96.93 ms/iter  (94.39 ms 102.58 ms)  97.68 ms 102.58 ms 102.58 ms
npm/string-width      8 chars ansi+emoji          3.92 µs/iter     (3.45 µs 4.57 µs)   4.09 µs   4.57 µs   4.57 µs
npm/string-width     80 chars ansi+emoji         24.46 µs/iter     (22.87 µs 4.2 ms)  23.54 µs  25.89 µs  27.41 µs
npm/string-width    800 chars ansi+emoji        259.62 µs/iter (246.76 µs 480.12 µs) 258.65 µs 349.84 µs 372.55 µs
npm/string-width  8,000 chars ansi+emoji          5.46 ms/iter     (5.41 ms 5.57 ms)   5.48 ms   5.55 ms   5.57 ms
npm/string-width 40,000 chars ansi+emoji        108.91 ms/iter  (107.55 ms 109.5 ms) 109.25 ms  109.5 ms  109.5 ms
npm/string-width     19 chars ansi+emoji+ascii    6.53 µs/iter     (6.35 µs 6.75 µs)   6.54 µs   6.75 µs   6.75 µs
npm/string-width    190 chars ansi+emoji+ascii   55.52 µs/iter  (52.59 µs 352.73 µs)  54.19 µs  80.77 µs 167.21 µs
npm/string-width  1,900 chars ansi+emoji+ascii  701.71 µs/iter (653.94 µs 893.78 µs)  715.3 µs 855.37 µs  872.9 µs
npm/string-width 19,000 chars ansi+emoji+ascii   27.19 ms/iter   (26.89 ms 27.41 ms)  27.28 ms  27.41 ms  27.41 ms
npm/string-width 95,000 chars ansi+emoji+ascii     3.68 s/iter        (3.66 s 3.7 s)    3.69 s     3.7 s     3.7 s

TypeScript 定義:

ts
namespace Bun {
  export function stringWidth(
    /**
     * 要測量的字符串
     */
    input: string,
    options?: {
      /**
       * 如果為 `true`,將 ANSI 轉義碼計為字符串寬度的一部分。如果為 `false`,計算字符串寬度時忽略 ANSI 轉義碼。
       *
       * @default false
       */
      countAnsiEscapeCodes?: boolean;
      /**
       * 當不明確且為 `true` 時,將 emoji 計為 1 個字符寬。如果為 `false`,emoji 計為 2 個字符寬。
       *
       * @default true
       */
      ambiguousIsNarrow?: boolean;
    },
  ): number;
}

Bun.fileURLToPath()

file:// URL 轉換為絕對路徑。

ts
const path = Bun.fileURLToPath(new URL("file:///foo/bar.txt"));
console.log(path); // "/foo/bar.txt"

Bun.pathToFileURL()

將絕對路徑轉換為 file:// URL。

ts
const url = Bun.pathToFileURL("/foo/bar.txt");
console.log(url); // "file:///foo/bar.txt"

Bun.gzipSync()

使用 zlib 的 GZIP 算法壓縮 Uint8Array

ts
const buf = Buffer.from("hello".repeat(100)); // Buffer 擴展自 Uint8Array
const compressed = Bun.gzipSync(buf);

buf; // => Uint8Array(500)
compressed; // => Uint8Array(30)

可選地,將參數對象作為第二個參數傳遞:

zlib 壓縮選項">

ts
export type ZlibCompressionOptions = {
  /**
   * 要使用的壓縮級別。必須在 `-1` 和 `9` 之間。
   * - 值 `-1` 使用默認壓縮級別(當前為 `6`)
   * - 值 `0` 不壓縮
   * - 值 `1` 提供最低壓縮,最快速度
   * - 值 `9` 提供最佳壓縮,最慢速度
   */
  level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  /**
   * 應為內部壓縮狀態分配多少內存。
   *
   * 值 `1` 使用最少內存但速度慢並降低壓縮比。
   *
   * 值 `9` 使用最大內存以獲得最佳速度。默認為 `8`。
   */
  memLevel?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  /**
   * 窗口大小的以 2 為底的對數(歷史記錄緩沖區的大小)。
   *
   * 此參數的較大值以內存使用為代價實現更好的壓縮。
   *
   * 支持以下值范圍:
   * - `9..15`:輸出將具有 zlib 頭和尾(Deflate)
   * - `-9..-15`:輸出將**不**具有 zlib 頭或尾(原始 Deflate)
   * - `25..31`(16+`9..15`):輸出將具有 gzip 頭和尾(gzip)
   *
   * gzip 頭將沒有文件名、沒有額外數據、沒有注釋、沒有修改時間(設置為零)且沒有頭 CRC。
   */
  windowBits?:
    | -9
    | -10
    | -11
    | -12
    | -13
    | -14
    | -15
    | 9
    | 10
    | 11
    | 12
    | 13
    | 14
    | 15
    | 25
    | 26
    | 27
    | 28
    | 29
    | 30
    | 31;
  /**
   * 調整壓縮算法。
   *
   * - `Z_DEFAULT_STRATEGY`:用於普通數據 **(默認)**
   * - `Z_FILTERED`:用於由過濾器或預測器生成的數據
   * - `Z_HUFFMAN_ONLY`:僅強制 Huffman 編碼(無字符串匹配)
   * - `Z_RLE`:將匹配距離限制為一(游程編碼)
   * - `Z_FIXED` 防止使用動態 Huffman 碼
   *
   * `Z_RLE` 旨在幾乎與 `Z_HUFFMAN_ONLY` 一樣快,但為 PNG 圖像數據提供更好的壓縮。
   *
   * `Z_FILTERED` 強制更多的 Huffman 編碼和更少的字符串匹配,它在某種程度上介於 `Z_DEFAULT_STRATEGY` 和 `Z_HUFFMAN_ONLY` 之間。
   * 過濾後的數據主要由小值組成,分布 somewhat 隨機。
   */
  strategy?: number;
};

Bun.gunzipSync()

使用 zlib 的 GUNZIP 算法解壓縮 Uint8Array

ts
const buf = Buffer.from("hello".repeat(100)); // Buffer 擴展自 Uint8Array
const compressed = Bun.gzipSync(buf);

const dec = new TextDecoder();
const uncompressed = Bun.gunzipSync(compressed);
dec.decode(uncompressed);
// => "hellohellohello..."

Bun.deflateSync()

使用 zlib 的 DEFLATE 算法壓縮 Uint8Array

ts
const buf = Buffer.from("hello".repeat(100));
const compressed = Bun.deflateSync(buf);

buf; // => Buffer(500)
compressed; // => Uint8Array(12)

第二個參數支持與 Bun.gzipSync 相同的配置選項集。


Bun.inflateSync()

使用 zlib 的 INFLATE 算法解壓縮 Uint8Array

ts
const buf = Buffer.from("hello".repeat(100));
const compressed = Bun.deflateSync(buf);

const dec = new TextDecoder();
const decompressed = Bun.inflateSync(compressed);
dec.decode(decompressed);
// => "hellohellohello..."

Bun.zstdCompress() / Bun.zstdCompressSync()

使用 Zstandard 算法壓縮 Uint8Array

ts
const buf = Buffer.from("hello".repeat(100));

// 同步
const compressedSync = Bun.zstdCompressSync(buf);
// 異步
const compressedAsync = await Bun.zstdCompress(buf);

// 使用壓縮級別(1-22,默認:3)
const compressedLevel = Bun.zstdCompressSync(buf, { level: 6 });

Bun.zstdDecompress() / Bun.zstdDecompressSync()

使用 Zstandard 算法解壓縮 Uint8Array

ts
const buf = Buffer.from("hello".repeat(100));
const compressed = Bun.zstdCompressSync(buf);

// 同步
const decompressedSync = Bun.zstdDecompressSync(compressed);
// 異步
const decompressedAsync = await Bun.zstdDecompress(compressed);

const dec = new TextDecoder();
dec.decode(decompressedSync);
// => "hellohellohello..."

Bun.inspect()

將對象序列化為 string,就像 console.log 打印的那樣。

ts
const obj = { foo: "bar" };
const str = Bun.inspect(obj);
// => '{\nfoo: "bar" \n}'

const arr = new Uint8Array([1, 2, 3]);
const str = Bun.inspect(arr);
// => "Uint8Array(3) [ 1, 2, 3 ]"

Bun.inspect.custom

這是 Bun 用於實現 Bun.inspect 的符號。你可以覆蓋此符號來自定義對象的打印方式。它與 Node.js 中的 util.inspect.custom 相同。

ts
class Foo {
  [Bun.inspect.custom]() {
    return "foo";
  }
}

const foo = new Foo();
console.log(foo); // => "foo"

Bun.inspect.table(tabularData, properties, options)

將表格數據格式化為字符串。類似於 console.table,但它返回字符串而不是打印到控制台。

ts
console.log(
  Bun.inspect.table([
    { a: 1, b: 2, c: 3 },
    { a: 4, b: 5, c: 6 },
    { a: 7, b: 8, c: 9 },
  ]),
);
//
// ┌───┬───┬───┬───┐
// │   │ a │ b │ c │
// ├───┼───┼───┼───┤
// │ 0 │ 1 │ 2 │ 3 │
// │ 1 │ 4 │ 5 │ 6 │
// │ 2 │ 7 │ 8 │ 9 │
// └───┴───┴───┴───┘

此外,你可以傳遞屬性名稱數組來僅顯示屬性的子集。

ts
console.log(
  Bun.inspect.table(
    [
      { a: 1, b: 2, c: 3 },
      { a: 4, b: 5, c: 6 },
    ],
    ["a", "c"],
  ),
);
//
// ┌───┬───┬───┐
// │   │ a │ c │
// ├───┼───┼───┤
// │ 0 │ 1 │ 3 │
// │ 1 │ 4 │ 6 │
// └───┴───┴───┘

你還可以通過傳遞 { colors: true } 有條件地啟用 ANSI 顏色。

ts
console.log(
  Bun.inspect.table(
    [
      { a: 1, b: 2, c: 3 },
      { a: 4, b: 5, c: 6 },
    ],
    {
      colors: true,
    },
  ),
);

Bun.nanoseconds()

返回自當前 bun 進程啟動以來的納秒數,作為 number。適用於高精度計時和基准測試。

ts
Bun.nanoseconds();
// => 7288958

Bun.readableStreamTo*()

Bun 實現了一組便利函數,用於異步消費 ReadableStream 的主體並將其轉換為各種二進制格式。

ts
const stream = (await fetch("https://bun.com")).body;
stream; // => ReadableStream

await Bun.readableStreamToArrayBuffer(stream);
// => ArrayBuffer

await Bun.readableStreamToBytes(stream);
// => Uint8Array

await Bun.readableStreamToBlob(stream);
// => Blob

await Bun.readableStreamToJSON(stream);
// => object

await Bun.readableStreamToText(stream);
// => string

// 將所有塊作為數組返回
await Bun.readableStreamToArray(stream);
// => unknown[]

// 將所有塊作為 FormData 對象返回(編碼為 x-www-form-urlencoded)
await Bun.readableStreamToFormData(stream);

// 將所有塊作為 FormData 對象返回(編碼為 multipart/form-data)
await Bun.readableStreamToFormData(stream, multipartFormBoundary);

Bun.resolveSync()

使用 Bun 的內部模塊解析算法解析文件路徑或模塊說明符。第一個參數是要解析的路徑,第二個參數是"根"。如果未找到匹配項,則拋出 Error

ts
Bun.resolveSync("./foo.ts", "/path/to/project");
// => "/path/to/project/foo.ts"

Bun.resolveSync("zod", "/path/to/project");
// => "/path/to/project/node_modules/zod/index.ts"

要相對於當前工作目錄解析,傳遞 process.cwd()"." 作為根。

ts
Bun.resolveSync("./foo.ts", process.cwd());
Bun.resolveSync("./foo.ts", "/path/to/project");

要相對於包含當前文件的目錄解析,傳遞 import.meta.dir

ts
Bun.resolveSync("./foo.ts", import.meta.dir);

Bun.stripANSI()

NOTE

比 `strip-ansi` 快約 6-57 倍的替代方案

Bun.stripANSI(text: string): string

從字符串中剝離 ANSI 轉義碼。這對於從終端輸出中移除顏色和格式很有用。

ts
const coloredText = "\u001b[31mHello\u001b[0m \u001b[32mWorld\u001b[0m";
const plainText = Bun.stripANSI(coloredText);
console.log(plainText); // => "Hello World"

// 適用於各種 ANSI 碼
const formatted = "\u001b[1m\u001b[4mBold and underlined\u001b[0m";
console.log(Bun.stripANSI(formatted)); // => "Bold and underlined"

Bun.stripANSI 比流行的 strip-ansi npm 包快得多:

bash
bun bench/snippets/strip-ansi.mjs
txt
cpu: Apple M3 Max
runtime: bun 1.2.21 (arm64-darwin)

benchmark                               avg (min … max) p75 / p99
------------------------------------------------------- ----------
Bun.stripANSI      11 chars no-ansi        8.13 ns/iter   8.27 ns
                                   (7.45 ns … 33.59 ns)  10.29 ns

Bun.stripANSI      13 chars ansi          51.68 ns/iter  52.51 ns
                                 (46.16 ns … 113.71 ns)  57.71 ns

Bun.stripANSI  16,384 chars long-no-ansi 298.39 ns/iter 305.44 ns
                                (281.50 ns … 331.65 ns) 320.70 ns

Bun.stripANSI 212,992 chars long-ansi    227.65 µs/iter 234.50 µs
                                (216.46 µs … 401.92 µs) 262.25 µs
bash
node bench/snippets/strip-ansi.mjs
txt
cpu: Apple M3 Max
runtime: node 24.6.0 (arm64-darwin)

benchmark                                avg (min … max) p75 / p99
-------------------------------------------------------- ---------
npm/strip-ansi      11 chars no-ansi      466.79 ns/iter 468.67 ns
                                 (454.08 ns … 570.67 ns) 543.67 ns

npm/strip-ansi      13 chars ansi         546.77 ns/iter 550.23 ns
                                 (532.74 ns … 651.08 ns) 590.35 ns

npm/strip-ansi  16,384 chars long-no-ansi   4.85 µs/iter   4.89 µs
                                     (4.71 µs … 5.00 µs)   4.98 µs

npm/strip-ansi 212,992 chars long-ansi      1.36 ms/iter   1.38 ms
                                     (1.27 ms … 1.73 ms)   1.49 ms

bun:jsc 中的 serializedeserialize

要將 JavaScript 值保存到 ArrayBuffer 並返回,使用 "bun:jsc" 模塊中的 serializedeserialize

js
import { serialize, deserialize } from "bun:jsc";

const buf = serialize({ foo: "bar" });
const obj = deserialize(buf);
console.log(obj); // => { foo: "bar" }

在內部,structuredClonepostMessage 以相同的方式序列化和反序列化。這將底層的 HTML 結構化克隆算法 作為 ArrayBuffer 暴露給 JavaScript。


bun:jsc 中的 estimateShallowMemoryUsageOf

estimateShallowMemoryUsageOf 函數返回對象內存用量的最佳估算值(以字節為單位),不包括屬性或它引用的其他對象的內存用量。要獲得准確的每個對象內存用量,使用 Bun.generateHeapSnapshot

js
import { estimateShallowMemoryUsageOf } from "bun:jsc";

const obj = { foo: "bar" };
const usage = estimateShallowMemoryUsageOf(obj);
console.log(usage); // => 16

const buffer = Buffer.alloc(1024 * 1024);
estimateShallowMemoryUsageOf(buffer);
// => 1048624

const req = new Request("https://bun.com");
estimateShallowMemoryUsageOf(req);
// => 167

const array = Array(1024).fill({ a: 1 });
// 數組通常在內存中不是連續存儲的,所以這不會返回有用的值(這不是 bug)。
estimateShallowMemoryUsageOf(array);
// => 16

Bun學習網由www.bunjs.com.cn整理維護