Skip to content

Bun.version

현재 실행 중인 bun CLI 의 버전을 포함하는 string 입니다.

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

이는 스크립트가 다른 스크립트에서 import 되는 것이 아니라 직접 실행되고 있는지 확인하는 데 특히 유용합니다.

ts
if (import.meta.path === Bun.main) {
  // 이 스크립트가 직접 실행됨
} else {
  // 이 파일이 다른 스크립트에서 import 됨
}

이는 Node.js 의 require.main = module 트릭 과 유사합니다.

Bun.sleep()

Bun.sleep(ms: number)

지정된 밀리초 후에 해결되는 Promise 를 반환합니다.

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

또는 Date 객체를 전달하여 해당 시점에 해결되는 Promise 를 받을 수도 있습니다.

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)

Bun.sleep 의 블로킹 동기 버전입니다.

ts
console.log("hello");
Bun.sleepSync(1000); // 스레드를 1 초 동안 차단
console.log("hello one second later!");

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 으로 래핑된 의사 난수 정수로 재설정됩니다. 이 카운터는 원자적이며 스레드 안전하므로, 동일한 타임스탬프에서 실행되는 동일한 프로세스 내의 많은 워커에서 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;

  // timestamp 만 전달하면 hex 문자열을 받습니다
  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)

await 또는 .then 없이 promise 의 결과를 읽지만, 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);

  // 비 promise 를 peek 하면 값 반환
  const value = peek(42);
  expect(value).toBe(42);

  // 보류 중인 promise 를 peek 하면 promise 를 다시 반환
  const pending = new Promise(() => {});
  expect(peek(pending)).toBe(pending);

  // 거부된 promise 를 peek 하면:
  // - 오류를 반환
  // - promise 를 처리된 것으로 표시하지 않음
  const rejected = Promise.reject(new Error("Successfully tested promise rejection"));
  expect(peek(rejected).message).toBe("Successfully tested promise rejection");
});

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

Bun.openInEditor()

기본 편집기에서 파일을 엽니다. Bun 은 $VISUAL 또는 $EDITOR 환경 변수를 통해 편집기를 자동 감지합니다.

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

bunfig.tomldebug.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 } });

세 번째 불리언 파라미터를 사용하여 "strict" 모드를 활성화할 수 있습니다. 이는 테스트 러너의 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

strict 모드에서는 다음이 동일하지 않은 것으로 간주됩니다:

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

// 배열의 undefined
Bun.deepEquals(["asdf"], ["asdf", undefined], true); // false

// 희소 배열
Bun.deepEquals([, 1], [undefined, 1], true); // false

// 객체 리터럴 vs 동일한 속성을 가진 인스턴스
class Foo {
  a = 1;
}
Bun.deepEquals(new Foo(), { a: 1 }, true); // false

Bun.escapeHTML()

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

입력 문자열에서 다음 문자를 이스케이프합니다:

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

이 함수는 대용량 입력에 최적화되어 있습니다. M1X 에서 이스케이프되는 데이터 양과 비 ASCII 텍스트 여부에 따라 480 MB/s - 20 GB/s 를 처리합니다. 비 문자열 타입은 이스케이프 전에 문자열로 변환됩니다.

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 이스케이프 코드가 포함되어 있는지 빠르게 확인
  • 터미널에서 문자열 너비 측정

이 API 는 인기 있는 "string-width" 패키지와 일치하도록 설계되어 기존 코드를 Bun 으로 쉽게 이식할 수 있으며 그 반대도 가능합니다.

이 벤치마크에서, Bun.stringWidth 는 약 500 자보다 큰 입력에 대해 string-width npm 패키지보다 약 6,756 배 빠릅니다. string-width 작업을 한 sindresorhus 에게 큰 감사를 드립니다!

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     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 초입니다. 단위 간 변환을 위한 빠른 참조:

단위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` 일 때 이모지를 1 문자 너비로 계산합니다. `false` 이면 이모지는 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 헤더나 푸터가 **없습니다** (Raw Deflate)
   * - `25..31` (16+`9..15`): 출력에 gzip 헤더와 푸터가 있습니다 (gzip)
   *
   * gzip 헤더에는 파일 이름, 추가 데이터, 주석, 수정 시간 (0 으로 설정) 및 헤더 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`: 허프만 인코딩만 강제 (문자열 일치 없음)
   * - `Z_RLE`: 일치 거리를 1 로 제한 (런 - 렝스 인코딩)
   * - `Z_FIXED` 는 동적 허프만 코드 사용 방지
   *
   * `Z_RLE` 는 `Z_HUFFMAN_ONLY` 와 거의 비슷하지만 PNG 이미지 데이터에 대해 더 나은 압축을 제공하도록 설계되었습니다.
   *
   * `Z_FILTERED` 는 더 많은 허프만 인코딩과 더 적은 문자열 매칭을 강제하며,
   * `Z_DEFAULT_STRATEGY` 와 `Z_HUFFMAN_ONLY` 사이에서 다소 중간입니다.
   * 필터링된 데이터는 대부분 작고 다소 무작위 분포를 가진 값으로 구성됩니다.
   */
  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()

console.log 로 출력될 때와 정확히 동일하게 객체를 string 으로 직렬화합니다.

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 가 throw 됩니다.

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:jscserialize & deserialize

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:jscestimateShallowMemoryUsageOf

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 by www.bunjs.com.cn 편집