Skip to content

Bun.version

سلسلة string تحتوي على إصدار bun CLI الذي يعمل حاليًا.

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

Bun.revision

إلتزام git لـ Bun الذي تم تجميعه لإنشاء bun CLI الحالي.

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 {
  // يتم استيراد هذا الملف من نص آخر
}

هذا مشابه لـ خدعة require.main = module في Node.js.

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

يمكنك التفكير في هذا كبديل مدمج لحزمة npm which.

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. هذا العداد ذري وآمن للخيوط، مما يعني أن استخدام Bun.randomUUIDv7() في العديد من Workers داخل نفس العملية التي تعمل في نفس الطابع الزمني لن يكون لها قيم عداد متصادمة.

الـ 8 بايتات الأخيرة من UUID هي قيمة عشوائية آمنة تشفيريًا. تستخدم نفس مولد الأرقام العشوائية المستخدم بواسطة 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;

  // إذا مررت طابع زمني فقط، تحصل على سلسلة hex
  function randomUUIDv7(timestamp?: number = Date.now()): string;
}

يمكنك اختياريًا تعيين الترميز إلى "buffer" للحصول على مخزن مؤقت 16 بايت بدلاً من سلسلة. هذا يمكن أن يتجنب أحيانًا تحويل السلسلة.

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

يتم دعم ترميزات base64 و base64url أيضًا عندما تريد سلسلة أقصر قليلاً.

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

Bun.peek()

Bun.peek(prom: Promise)

يقرأ نتيجة الوعد بدون await أو .then، لكن فقط إذا كان الوعد قد اكتمل أو رُفض بالفعل.

ts
import { peek } from "bun";

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

// بدون await!
const result = peek(promise);
console.log(result); // "hi"

هذا مهم عند محاولة تقليل عدد microticks الزائدة في الكود الحساس للأداء. إنها واجهة برمجة تطبيقات متقدمة وربما لا يجب عليك استخدامها ما لم تكن تعرف ما تفعله.

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

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

  // لا حاجة لـ await!
  expect(peek(promise)).toBe(true);

  // إذا نظرنا مرة أخرى، ترجع نفس القيمة
  const again = peek(promise);
  expect(again).toBe(true);

  // إذا نظرنا إلى غير وعد، ترجع القيمة
  const value = peek(42);
  expect(value).toBe(42);

  // إذا نظرنا إلى وعد معلق، ترجع الوعد مرة أخرى
  const pending = new Promise(() => {});
  expect(peek(pending)).toBe(pending);

  // إذا نظرنا إلى وعد مرفوض، فإنه:
  // - يرجع الخطأ
  // - لا يميز الوعد كمعالج
  const rejected = Promise.reject(new Error("تم اختبار رفض الوعد بنجاح"));
  expect(peek(rejected).message).toBe("تم اختبار رفض الوعد بنجاح");
});

دالة peek.status تتيح لك قراءة حالة الوعد بدون حله.

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

يفتح ملفًا في المحرر الافتراضي الخاص بك. يكتشف Bun محررك تلقائيًا عبر متغيرات البيئة $VISUAL أو $EDITOR.

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

يمكنك تجاوز هذا عبر إعداد debug.editor في bunfig.toml الخاص بك.

toml
[debug] 
editor = "code"

أو حدد محررًا مع معلمة editor. يمكنك أيضًا تحديد رقم سطر وعمود.

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

Bun.deepEquals()

يتحقق بشكل متكرر مما إذا كان كائنان متماثلين. يُستخدم داخليًا بواسطة expect().toEqual() في 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 } });

يمكن استخدام معلمة منطقية ثالثة لتمكين الوضع "الصارم". يُستخدم بواسطة 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 والرموز التعبيرية والأحرف العريضة.

مثال للاستخدام:

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

هذا مفيد لـ:

  • محاذاة النص في الطرفية
  • التحقق بسرعة مما إذا كانت السلسلة تحتوي على رموز هروب ANSI
  • قياس عرض سلسلة في الطرفية

تم تصميم هذه الواجهة لتتطابق مع حزمة "string-width" الشائعة، بحيث يمكن نقل الكود الحالي بسهولة إلى Bun والعكس.

في هذا المعيار، Bun.stringWidth أسرع بـ ~6,756 مرة من حزمة npm string-width للمدخلات الأكبر من حوالي 500 حرف. شكر كبير لـ sindresorhus على عمله على 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

لجعل Bun.stringWidth سريعًا، قمنا بتنفيذه في Zig باستخدام تعليمات SIMD المحسنة، مع حساب ترميزات Latin1 و UTF-16 و UTF-8. يجتاز اختبارات string-width.

عرض المعيار الكامل">

كتذكير، 1 نانوثانية (ns) هي جزء من مليار من الثانية. إليك مرجع سريع لتحويل الوحدات:

وحدة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 µس   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`، احسب الرموز التعبيرية كحرف واحد عريض. إذا `false`، يتم حساب الرموز التعبيرية كحرفين عريضين.
       *
       * @default true
       */
      ambiguousIsNarrow?: boolean;
    },
  ): number;
}

Bun.fileURLToPath()

يحول URL file:// إلى مسار مطلق.

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

Bun.pathToFileURL()

يحول مسارًا مطلقًا إلى URL file://.

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

Bun.gzipSync()

يضغط Uint8Array باستخدام خوارزمية GZIP من zlib.

ts
const buf = Buffer.from("hello".repeat(100)); // Buffer extends 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 (Raw 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`.
   * تتكون البيانات المصفاة في الغالب من قيم صغيرة مع توزيع عشوائي إلى حد ما.
   */
  strategy?: number;
};

Bun.gunzipSync()

يفك ضغط Uint8Array باستخدام خوارزمية GUNZIP من 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()

يضغط Uint8Array باستخدام خوارزمية DEFLATE من zlib.

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

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

الوسيطة الثانية تدعم نفس مجموعة خيارات التكوين مثل Bun.gzipSync.


Bun.inflateSync()

يفك ضغط Uint8Array باستخدام خوارزمية INFLATE من 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()

يضغط Uint8Array باستخدام خوارزمية Zstandard.

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

يفك ضغط Uint8Array باستخدام خوارزمية Zstandard.

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. يمكنك تجاوز هذا لتخصيص كيفية طباعة كائناتك. إنه مطابق لـ util.inspect.custom في Node.js.

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

يمكنك أيضًا تمكين ألوان ANSI شرطيًا عن طريق تمرير { colors: true }.

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 أسرع بكثير من حزمة 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 في bun:jsc

لحفظ قيمة JavaScript في ArrayBuffer وإرجاعها، استخدم serialize و deserialize من وحدة "bun:jsc".

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

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

داخليًا، structuredClone و postMessage يسلسلان ويفككان التسلسل بنفس الطريقة. هذا يعرض خوارزمية الاستنساخ الهيكلي HTML الأساسية لـ JavaScript كـ ArrayBuffer.


estimateShallowMemoryUsageOf في bun:jsc

دالة 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 });
// المصفوفات عادة لا يتم تخزينها بشكل متجاور في الذاكرة، لذا لن ترجع هذه قيمة مفيدة (وهذا ليس خطأ).
estimateShallowMemoryUsageOf(array);
// => 16

Bun بواسطة www.bunjs.com.cn تحرير