Skip to content

Bun.version

Una string contenente la versione del CLI bun attualmente in esecuzione.

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

Bun.revision

Il commit git di Bun che è stato compilato per creare l'attuale CLI bun.

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

Bun.env

Un alias per process.env.

Bun.main

Un percorso assoluto al punto di ingresso del programma corrente (il file che è stato eseguito con bun run).

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

Questo è particolarmente utile per determinare se uno script viene eseguito direttamente, invece di essere importato da un altro script.

ts
if (import.meta.path === Bun.main) {
  // questo script viene eseguito direttamente
} else {
  // questo file viene importato da un altro script
}

Questo è analogo al trucco require.main = module in Node.js.

Bun.sleep()

Bun.sleep(ms: number)

Restituisce una Promise che si risolve dopo il numero di millisecondi specificato.

ts
console.log("hello");
await Bun.sleep(1000);
console.log("hello one second later!");

In alternativa, passa un oggetto Date per ricevere una Promise che si risolve in quel momento.

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

console.log("hello");
await Bun.sleep(oneSecondInFuture);
console.log("hello one second later!");

Bun.sleepSync()

Bun.sleepSync(ms: number)

Una versione sincrona bloccante di Bun.sleep.

ts
console.log("hello");
Bun.sleepSync(1000); // blocks thread for one second
console.log("hello one second later!");

Bun.which()

Bun.which(bin: string)

Restituisce il percorso a un eseguibile, simile a digitare which nel tuo terminale.

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

Di default Bun guarda la variabile d'ambiente PATH corrente per determinare il percorso. Per configurare PATH:

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

Passa un'opzione cwd per risolvere l'eseguibile da una directory specifica.

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

console.log(ls); // null

Puoi pensare a questo come a un'alternativa integrata al pacchetto npm which.

Bun.randomUUIDv7()

Bun.randomUUIDv7() restituisce un UUID v7, che è monotonic e adatto per l'ordinamento e i database.

ts
import { randomUUIDv7 } from "bun";

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

Un UUID v7 è un valore a 128 bit che codifica il timestamp corrente, un valore casuale e un contatore. Il timestamp è codificato usando i 48 bit più bassi, e il valore casuale e il contatore sono codificati usando i bit rimanenti.

Il parametro timestamp predefinito è il tempo corrente in millisecondi. Quando il timestamp cambia, il contatore viene reimpostato a un intero pseudo-casuale racchiuso a 4096. Questo contatore è atomico e thread-safe, il che significa che usare Bun.randomUUIDv7() in molti Worker all'interno dello stesso processo in esecuzione allo stesso timestamp non avrà valori del contatore in collisione.

Gli ultimi 8 byte dell'UUID sono un valore casuale crittograficamente sicuro. Usa lo stesso generatore di numeri casuali usato da crypto.randomUUID() (che viene da BoringSSL, che a sua volta viene dal generatore di numeri casuali specifico della piattaforma generalmente fornito dall'hardware sottostante).

ts
namespace Bun {
  function randomUUIDv7(encoding?: "hex" | "base64" | "base64url" = "hex", timestamp?: number = Date.now()): string;
  /**
   * If you pass "buffer", you get a 16-byte buffer instead of a string.
   */
  function randomUUIDv7(encoding: "buffer", timestamp?: number = Date.now()): Buffer;

  // If you only pass a timestamp, you get a hex string
  function randomUUIDv7(timestamp?: number = Date.now()): string;
}

Opzionalmente, puoi impostare la codifica su "buffer" per ottenere un buffer di 16 byte invece di una stringa. Questo a volte può evitare l'overhead della conversione di stringa.

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

Le codifiche base64 e base64url sono supportate anche quando vuoi una stringa leggermente più corta.

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

Bun.peek()

Bun.peek(prom: Promise)

Legge il risultato di una promise senza await o .then, ma solo se la promise è già stata mantenuta o rifiutata.

ts
import { peek } from "bun";

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

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

Questo è importante quando si tenta di ridurre il numero di microtick extra nel codice sensibile alle prestazioni. È un'API avanzata e probabilmente non dovresti usarla a meno che tu non sappia cosa stai facendo.

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

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

  // no await necessary!
  expect(peek(promise)).toBe(true);

  // if we peek again, it returns the same value
  const again = peek(promise);
  expect(again).toBe(true);

  // if we peek a non-promise, it returns the value
  const value = peek(42);
  expect(value).toBe(42);

  // if we peek a pending promise, it returns the promise again
  const pending = new Promise(() => {});
  expect(peek(pending)).toBe(pending);

  // If we peek a rejected promise, it:
  // - returns the error
  // - does not mark the promise as handled
  const rejected = Promise.reject(new Error("Successfully tested promise rejection"));
  expect(peek(rejected).message).toBe("Successfully tested promise rejection");
});

La funzione peek.status ti permette di leggere lo stato di una promise senza risolverla.

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("oh nooo"));
  expect(peek.status(rejected)).toBe("rejected");
});

Bun.openInEditor()

Apre un file nel tuo editor predefinito. Bun rileva automaticamente il tuo editor tramite le variabili d'ambiente $VISUAL o $EDITOR.

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

Puoi sovrascrivere questo tramite l'impostazione debug.editor nel tuo bunfig.toml.

toml
[debug] 
editor = "code"

Oppure specifica un editor con il parametro editor. Puoi anche specificare un numero di riga e colonna.

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

Bun.deepEquals()

Verifica ricorsivamente se due oggetti sono equivalenti. Questo è usato internamente da expect().toEqual() in bun:test.

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 } });

Un terzo parametro booleano può essere usato per abilitare la modalità "strict". Questo è usato da expect().toStrictEqual() nel test runner.

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

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

In modalità strict, i seguenti sono considerati disuguali:

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

// undefined in arrays
Bun.deepEquals(["asdf"], ["asdf", undefined], true); // false

// sparse arrays
Bun.deepEquals([, 1], [undefined, 1], true); // false

// object literals vs instances w/ same properties
class Foo {
  a = 1;
}
Bun.deepEquals(new Foo(), { a: 1 }, true); // false

Bun.escapeHTML()

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

Scappa i seguenti caratteri da una stringa di input:

  • " diventa "
  • & diventa &
  • ' diventa '
  • < diventa <
  • > diventa >

Questa funzione è ottimizzata per input grandi. Su un M1X, elabora 480 MB/s - 20 GB/s, a seconda di quanti dati vengono scappati e se c'è testo non-ascii. I tipi non-stringa verranno convertiti in stringa prima dello scappamento.

Bun.stringWidth()

NOTE

~6,756x più veloce alternativa a `string-width`

Ottiene il conteggio delle colonne di una stringa come verrebbe visualizzata in un terminale. Supporta codici di escape ANSI, emoji e caratteri larghi.

Esempio di utilizzo:

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

Questo è utile per:

  • Allineare il testo in un terminale
  • Controllare rapidamente se una stringa contiene codici di escape ANSI
  • Misurare la larghezza di una stringa in un terminale

Questa API è progettata per corrispondere al popolare pacchetto "string-width", così che il codice esistente possa essere facilmente portato a Bun e viceversa.

In questo benchmark, Bun.stringWidth è circa ~6,756x più veloce del pacchetto npm string-width per input maggiori di circa 500 caratteri. Un grande ringraziamento a sindresorhus per il loro lavoro su string-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

Per rendere Bun.stringWidth veloce, l'abbiamo implementato in Zig usando istruzioni SIMD ottimizzate, tenendo conto delle codifiche Latin1, UTF-16 e UTF-8. Passa i test di string-width.

Visualizza benchmark completo">

Come promemoria, 1 nanosecondo (ns) è un miliardesimo di secondo. Ecco una guida rapida per convertire tra unità:

Unità1 Millisecondo
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

Definizione TypeScript:

ts
namespace Bun {
  export function stringWidth(
    /**
     * The string to measure
     */
    input: string,
    options?: {
      /**
       * If `true`, count ANSI escape codes as part of the string width. If `false`, ANSI escape codes are ignored when calculating the string width.
       *
       * @default false
       */
      countAnsiEscapeCodes?: boolean;
      /**
       * When it's ambiugous and `true`, count emoji as 1 characters wide. If `false`, emoji are counted as 2 character wide.
       *
       * @default true
       */
      ambiguousIsNarrow?: boolean;
    },
  ): number;
}

Bun.fileURLToPath()

Converte un URL file:// in un percorso assoluto.

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

Bun.pathToFileURL()

Converte un percorso assoluto in un URL file://.

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

Bun.gzipSync()

Comprime un Uint8Array usando l'algoritmo GZIP di zlib.

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

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

Opzionalmente, passa un oggetto parametri come secondo argomento:

Opzioni compressione zlib">

ts
export type ZlibCompressionOptions = {
  /**
   * The compression level to use. Must be between `-1` and `9`.
   * - A value of `-1` uses the default compression level (Currently `6`)
   * - A value of `0` gives no compression
   * - A value of `1` gives least compression, fastest speed
   * - A value of `9` gives best compression, slowest speed
   */
  level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  /**
   * How much memory should be allocated for the internal compression state.
   *
   * A value of `1` uses minimum memory but is slow and reduces compression ratio.
   *
   * A value of `9` uses maximum memory for optimal speed. The default is `8`.
   */
  memLevel?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  /**
   * The base 2 logarithm of the window size (the size of the history buffer).
   *
   * Larger values of this parameter result in better compression at the expense of memory usage.
   *
   * The following value ranges are supported:
   * - `9..15`: The output will have a zlib header and footer (Deflate)
   * - `-9..-15`: The output will **not** have a zlib header or footer (Raw Deflate)
   * - `25..31` (16+`9..15`): The output will have a gzip header and footer (gzip)
   *
   * The gzip header will have no file name, no extra data, no comment, no modification time (set to zero) and no header CRC.
   */
  windowBits?:
    | -9
    | -10
    | -11
    | -12
    | -13
    | -14
    | -15
    | 9
    | 10
    | 11
    | 12
    | 13
    | 14
    | 15
    | 25
    | 26
    | 27
    | 28
    | 29
    | 30
    | 31;
  /**
   * Tunes the compression algorithm.
   *
   * - `Z_DEFAULT_STRATEGY`: For normal data **(Default)**
   * - `Z_FILTERED`: For data produced by a filter or predictor
   * - `Z_HUFFMAN_ONLY`: Force Huffman encoding only (no string match)
   * - `Z_RLE`: Limit match distances to one (run-length encoding)
   * - `Z_FIXED` prevents the use of dynamic Huffman codes
   *
   * `Z_RLE` is designed to be almost as fast as `Z_HUFFMAN_ONLY`, but give better compression for PNG image data.
   *
   * `Z_FILTERED` forces more Huffman coding and less string matching, it is
   * somewhat intermediate between `Z_DEFAULT_STRATEGY` and `Z_HUFFMAN_ONLY`.
   * Filtered data consists mostly of small values with a somewhat random distribution.
   */
  strategy?: number;
};

Bun.gunzipSync()

Decomprime un Uint8Array usando l'algoritmo GUNZIP di zlib.

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

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

Bun.deflateSync()

Comprime un Uint8Array usando l'algoritmo DEFLATE di zlib.

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

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

Il secondo argomento supporta lo stesso insieme di opzioni di configurazione di Bun.gzipSync.


Bun.inflateSync()

Decomprime un Uint8Array usando l'algoritmo INFLATE di zlib.

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()

Comprime un Uint8Array usando l'algoritmo Zstandard.

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

// Synchronous
const compressedSync = Bun.zstdCompressSync(buf);
// Asynchronous
const compressedAsync = await Bun.zstdCompress(buf);

// With compression level (1-22, default: 3)
const compressedLevel = Bun.zstdCompressSync(buf, { level: 6 });

Bun.zstdDecompress() / Bun.zstdDecompressSync()

Decomprime un Uint8Array usando l'algoritmo Zstandard.

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

// Synchronous
const decompressedSync = Bun.zstdDecompressSync(compressed);
// Asynchronous
const decompressedAsync = await Bun.zstdDecompress(compressed);

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

Bun.inspect()

Serializza un oggetto in una string esattamente come verrebbe stampato da 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

Questo è il simbolo che Bun usa per implementare Bun.inspect. Puoi sovrascriverlo per personalizzare come i tuoi oggetti vengono stampati. È identico a util.inspect.custom in Node.js.

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

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

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

Formatta dati tabulari in una stringa. Come console.table, ma restituisce una stringa invece di stampare sulla console.

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 │
// └───┴───┴───┴───┘

Inoltre, puoi passare un array di nomi di proprietà per visualizzare solo un sottoinsieme di proprietà.

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 │
// └───┴───┴───┘

Puoi anche abilitare condizionalmente i colori ANSI passando { colors: true }.

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

Bun.nanoseconds()

Restituisce il numero di nanosecondi da quando il processo bun corrente è iniziato, come number. Utile per timing e benchmarking di alta precisione.

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

Bun.readableStreamTo*()

Bun implementa un insieme di funzioni di utilità per consumare asincronamente il corpo di un ReadableStream e convertirlo in vari formati binari.

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

// returns all chunks as an array
await Bun.readableStreamToArray(stream);
// => unknown[]

// returns all chunks as a FormData object (encoded as x-www-form-urlencoded)
await Bun.readableStreamToFormData(stream);

// returns all chunks as a FormData object (encoded as multipart/form-data)
await Bun.readableStreamToFormData(stream, multipartFormBoundary);

Bun.resolveSync()

Risolve un percorso di file o un identificatore di modulo usando l'algoritmo di risoluzione dei moduli interno di Bun. Il primo argomento è il percorso da risolvere, e il secondo argomento è la "root". Se non viene trovata alcuna corrispondenza, viene lanciato un 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"

Per risolvere relativamente alla directory di lavoro corrente, passa process.cwd() o "." come root.

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

Per risolvere relativamente alla directory contenente il file corrente, passa import.meta.dir.

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

Bun.stripANSI()

NOTE

~6-57x più veloce alternativa a `strip-ansi`

Bun.stripANSI(text: string): string

Rimuove i codici di escape ANSI da una stringa. Utile per rimuovere colori e formattazione dall'output del terminale.

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

// Works with various ANSI codes
const formatted = "\u001b[1m\u001b[4mBold and underlined\u001b[0m";
console.log(Bun.stripANSI(formatted)); // => "Bold and underlined"

Bun.stripANSI è significativamente più veloce del popolare pacchetto npm strip-ansi:

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

serialize & deserialize in bun:jsc

Per salvare un valore JavaScript in un ArrayBuffer e viceversa, usa serialize e deserialize dal modulo "bun:jsc".

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

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

Internamente, structuredClone e postMessage serializzano e deserializzano allo stesso modo. Questo espone l'Algoritmo di Clonazione Strutturata HTML sottostante a JavaScript come ArrayBuffer.


estimateShallowMemoryUsageOf in bun:jsc

La funzione estimateShallowMemoryUsageOf restituisce una stima del miglior sforzo dell'utilizzo della memoria di un oggetto in byte, escludendo l'utilizzo della memoria delle proprietà o di altri oggetti a cui fa riferimento. Per un utilizzo della memoria per-oggetto accurato, usa 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 });
// Arrays are usually not stored contiguously in memory, so this will not return a useful value (which isn't a bug).
estimateShallowMemoryUsageOf(array);
// => 16

Bun a cura di www.bunjs.com.cn